【问题标题】:How can I execute two threads asynchronously using boost?如何使用 boost 异步执行两个线程?
【发布时间】:2012-09-08 09:05:22
【问题描述】:

我有这本书“超越 C++ 标准库”,并且没有使用 boost 的多线程示例。有人可以向我展示一个简单的示例,其中两个线程使用 boost 执行 - 让我们说异步?

【问题讨论】:

标签: c++ multithreading unix boost c++11


【解决方案1】:

这是我最小的 Boost 线程示例。

#include <boost/thread.hpp>
#include <iostream>

using namespace std;

void ThreadFunction()
{
    int counter = 0;

    for(;;)
    {
        cout << "thread iteration " << ++counter << " Press Enter to stop" << endl;

        try
        {
            // Sleep and check for interrupt.
            // To check for interrupt without sleep,
            // use boost::this_thread::interruption_point()
            // which also throws boost::thread_interrupted
            boost::this_thread::sleep(boost::posix_time::milliseconds(500));
        }
        catch(boost::thread_interrupted&)
        {
            cout << "Thread is stopped" << endl;
            return;
        }
    }
}

int main()
{
    // Start thread
    boost::thread t(&ThreadFunction);

    // Wait for Enter 
    char ch;
    cin.get(ch);

    // Ask thread to stop
    t.interrupt();

    // Join - wait when thread actually exits
    t.join();
    cout << "main: thread ended" << endl;

    return 0;
}

【讨论】:

  • 太棒了——第一行就是这么简单。我理解您对这条线的评论,但为什么“join()”会这样命名?那是同步程序流吗? Main() 在你的线程完成之前不会终止?
  • join 同步等待线程退出。如果没有这一行,程序可能会在工作线程仍在运行时退出。该线程将被操作系统杀死,但这不是干净的解决方案。
  • 所以,这段代码展示了如何:启动线程,通过发送中断请求停止线程并等待其执行。线程代码必须响应中断请求。另请参阅:boost.org/doc/libs/1_41_0/doc/html/thread/…,预定义中断点
  • 虽然您知识渊博,但我认为您无法回答 boost vs native Unix thread 的问题?谢谢,我很感激。
  • 我不知道这个。在最坏的情况下,即使 boost 线程实现在启动/停止操作上稍慢,线程本身在两种情况下也应该具有相同的性能。 Boost 线程在任何支持的平台上的本机线程上实现。
猜你喜欢
  • 1970-01-01
  • 2020-12-06
  • 2016-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 1970-01-01
相关资源
最近更新 更多