Dani Dani - 9 months ago 130
C++ Question

Run boost asio io_service forever

I call

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
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:


Answer Source

The io_service::work object exists for this purpose.