Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent boost::asio::io_context from returning when there is no more work to do

Tags:

c++

boost-asio

boost::asio::io_context::run() does return when no work is pending. I would like to avoid this behavior, so that run() does wait indefinitely for new works, with the possibility to stop it from another thread.

This could be done, I guess, by starting an infinitely long timer in the io_context, and by calling cancel() on that timer when we want run() to return.

Is this a proper approach and is there a clean way to do this?

like image 720
galinette Avatar asked Mar 05 '23 11:03

galinette


1 Answers

You can use executor_work_guard. In ctor it takes executor from io_context instance and call on_work_started on this executor what means that io_context::run doesn't end when there is no work to do see reference.

This ensures that the io_context's run() and run_one() functions do not exit while the work is underway.

So the simple code looks like

  boost::asio::io_context io;
  boost::asio::executor_work_guard<decltype(io.get_executor())> work{io.get_executor()};

  io.run(); // [1]
  cout << "you will never see this line" << endl;

code hangs in 1 line. io_context::run might end when work destructor was called.

On older boost or asio versions, the equivalent class is io_service::work

like image 50
rafix07 Avatar answered Apr 27 '23 02:04

rafix07