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

Viewed 476

In the main thread, I'm creating 8 std::threads in a loop. All these threads will ultimately call _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_services but I want to be sure that all the threads have started running their io_services i.e. all of them have called _ios.run() and are ready to process jobs.

Is there a way to query an io_serivce for its status? If yes, then I could query all the threads' io_services one by one to check if they are ready.

1 Answers

You can use the stopped member function. According to the Boost Asio Documentation:

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. When an io_context object is stopped, calls to run(), run_one(), poll() or poll_one() will return immediately without invoking any handlers.

Using !_ios.stopped() you will know if _ios is still running.

Related