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

时间:2012-09-15 12:30:42

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

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

1 个答案:

答案 0 :(得分: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;
}