如何使用boost异步执行两个线程?

use*_*112 18 c++ unix multithreading boost c++11

我有"超出C++标准库"的书,并且没有使用boost的多线程示例.有人会非常友好地向我展示一个简单的例子,其中两个线程使用boost执行 - 让我们说是异步的吗?

Ale*_*x F 38

这是我最小的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;
}
Run Code Online (Sandbox Code Playgroud)

  • 同步连接等待线程退出.如果没有这一行,程序可能会在工作线程仍在运行时退出.这个线程将被OS杀死,但这不是干净的解决方案. (3认同)