有一个使用boost::asio的例子。
srv.run ();来执行线程中的任务?int main()
{
    boost::asio::io_service srv;
    boost::asio::io_service::work work(srv);
    boost::thread_group thr_grp;
    thr_grp.create_thread(boost::bind(&boost::asio::io_service::run, &srv));
    thr_grp.create_thread(boost::bind(&boost::asio::io_service::run, &srv));
    srv.post(boost::bind(f1, 123));
    srv.post(boost::bind(f1, 321));
    //sync
    srv.post(boost::bind(f2, 456));
    srv.post(boost::bind(f2, 654));
    //sync
    srv.stop();
    thr_grp.join();
}更新:,当使用io_service而不使用io_service::work时,轮询和运行有什么区别?
int main()
{
    boost::asio::io_service srv;
    //boost::asio::io_service::work work(srv);
    std::vector<boost::thread> thr_grp;
    srv.post(boost::bind(f1, 123));
    srv.post(boost::bind(f1, 321));
    //sync
    srv.post(boost::bind(f2, 456));
    srv.post(boost::bind(f2, 654));
    //sync
    // What is the difference between the poll and run, when io_service without work?
    thr_grp.emplace_back(boost::bind(&boost::asio::io_service::poll, &srv));// poll or run?
    thr_grp.emplace_back(boost::bind(&boost::asio::io_service::run, &srv));// poll or run? 
    srv.stop();
    for(auto &i : thr_grp) i.join();
    int b;
    std::cin >> b;
    return 0;
}发布于 2013-06-17 21:41:48
当调用io_service::run方法时没有一个work对象,它将立即返回。通常情况下,这不是大多数开发人员正在寻找的行为。当然也有一些例外,但大多数开发人员都希望指定一个线程来处理所有的异步处理,并且在被告知之前不希望该线程退出。这就是您的代码示例所做的。
io_service::run方法指定为create_thread方法中的委托或函数指针。因此,当从create_thread方法创建线程时,它将调用io_service::run方法,并将io_service对象作为参数传递。通常,一个io_service对象可以与多个套接字对象一起使用。
当关闭应用程序或不再需要所有客户端/服务器之间的通信时,通常会调用停止方法,并且不需要启动任何新的连接。
https://stackoverflow.com/questions/17156541
复制相似问题