【问题标题】:Why do we need to use boost::asio::io_service::work?为什么我们需要使用 boost::asio::io_service::work?
【发布时间】:2013-06-13 22:32:47
【问题描述】:

有一个使用 boost::asio 的例子。

  1. 为什么这个例子使用 boost::asio::io_service::work ?
  2. 为什么不调用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,poll和run有什么区别?

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;
}

【问题讨论】:

    标签: c++ boost-asio


    【解决方案1】:

    当在没有工作对象的情况下调用io_service::run 方法时,它会立即返回。通常,这不是大多数开发人员正在寻找的行为。当然也有一些例外,但大多数开发人员都希望指定一个线程来处理所有异步处理,并且在被告知之前不希望该线程退出。这就是您的代码示例所做的。

    io_service::run 方法在 create_thread 方法中被指定为委托或函数指针。因此,当从create_thread 方法创建线程时,它将调用io_service::run 方法并将io_service 对象作为参数传递。通常一个io_service 对象可以与多个套接字对象一起使用。

    当关闭应用程序或不再需要所有客户端/服务器之间的通信并且预计不需要启动任何新连接时,通常会调用 stop 方法。

    【讨论】:

    • 谢谢!但是,当没有 io_service::work 使用 io_service 时,poll 和 run 有什么区别?我在没有工作的情况下添加了第二个示例。根据这种情况下的外部行为,它们(轮询和运行)以 100% 相同的方式运行?
    • Sam Miller 在他对 question 的回答中对 poll 和 run 之间的区别有一个很好的回答
    • work 对象已弃用。请查看完整示例:stackoverflow.com/a/56642587/3082081
    猜你喜欢
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多