首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用boost异步执行两个线程?

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

Stack Overflow用户
提问于 2012-09-15 20:30:42
回答 1查看 28.3K关注 0票数 18

我有一本书“超越C++标准库”,但是没有使用boost进行多线程的例子。有没有人可以给我展示一个简单的例子,其中两个线程使用boost执行--比如说异步执行?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-15 20:49:44

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

代码语言:javascript
复制
#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;
}
票数 38
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12437395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档