简体   繁体   English

如何检查 boost::asio::io_service 是否已开始运行?

[英]How to check if boost::asio::io_service has started running?

In the main thread, I'm creating 8 std::thread s in a loop.在主线程中,我在循环中创建 8 个std::thread All these threads will ultimately call _ios.run() // _ios is per thread .所有这些线程最终都会调用_ios.run() // _ios is per thread

In the Class definition:在类定义中:

boost::asio::io_service                           _ios;
boost::optional<boost::asio::io_service::work>    _work;
std::thread                                       _thread;

Class constructor:类构造函数:

{
      _work = boost::in_place(boost::ref(_ios));
      _thread = std::thread{[this] () {
              setup_a_few_stuffs();
              _ios.run();
          }
      };
}

In the main thread, I would like to post jobs to these io_service s but I want to be sure that all the threads have started running their io_service s ie all of them have called _ios.run() and are ready to process jobs.在主线程中,我想将作业发布到这些io_service但我想确保所有线程都已开始运行它们的io_service即它们都已调用_ios.run()并准备好处理作业。

Is there a way to query an io_serivce for its status?有没有办法查询io_serivce的状态? If yes, then I could query all the threads' io_service s one by one to check if they are ready.如果是,那么我可以一一查询所有线程的io_service以检查它们是否准备就绪。

You can use the stopped member function .您可以使用已stopped成员函数 According to the Boost Asio Documentation :根据Boost Asio 文档

This function is used to determine whether an io_context object has been stopped, either through an explicit call to stop() , or due to running out of work.此函数用于确定io_context对象是否已通过显式调用stop()或由于工作用完而stop() When an io_context object is stopped, calls to run() , run_one() , poll() or poll_one() will return immediately without invoking any handlers.io_context对象停止时,对run()run_one()poll()poll_one()调用将立即返回而不调用任何处理程序。

Using !_ios.stopped() you will know if _ios is still running.使用!_ios.stopped()您将知道_ios是否仍在运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM