Typically the pattern is to dispatch on the io_service in a separate thread, for example:
_thread.reset(new std::thread([&]() { _service.run(); }); // so the dispatching here is in a thread
Subsequently, if you want to stop it and wait for it to finish cleanly, then the best way is:
_service.stop();
_thread->join();
This way the calling thread is blocked until the dispatch thread terminates (which happens when the call to execute the last handler (run()
) completes. There is no way (AFAIK) of knowing whether the io_service ran out of work or whether stop()
was called, you can certainly prevent the former by instantiating an io_service::work
on the service. See the docs.