Daniel
Daniel

Reputation: 31579

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();
}

Upvotes: 6

Views: 2983

Answers (1)

Ralf
Ralf

Reputation: 9573

The io_service::work object exists for this purpose.

Upvotes: 7

Related Questions