Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run boost asio io_service forever

I call boost::asio::io_service::run() and it returns immediately since it has no jobs to do.
A different thread will queue work later on, but I don't want the run thread to exit.
On solution is to busy wait on run:

while(true) service.run();

But that would waste CPU when there is no work to do.
Another way is to wait on an event that is raised every time something is queued to the service.
This way has a race: If one thread stops doing work and then a second thread posts work and raises the event before the first has a chance to wait on it, the first would wait forever.
I would rather avoid that and have the service know when there is work to do.
Is it possible to do something like:

while(true)
{
    service.wait_for_work();
    service.run();
}
like image 309
Dani Avatar asked Oct 29 '16 18:10

Dani


1 Answers

The io_service::work object exists for this purpose.

like image 91
Ralf Avatar answered Sep 24 '22 05:09

Ralf