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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With