run()
is a blocking call, and will execute all events that it can before returning. It will only return if there are no more events to handle. Once it returns, you must call reset()
on the io_service before calling run()
again.
You can have multiple threads calling run()
- this is not a problem, and you don't need the infinite loop as long as the io_service has some work to do. The normal pattern for this is to create a work
object on the io_service which will force run()
to never return. This does mean that you explicitly have to call stop()
on the io_service when you are done as it will never naturally exit.
If you setup a work
on the io_service, it will never naturally exit and therefore you will never need to call reset()
.
work some_work(m_IoService); // this will keep the io_service live.
for( unsigned int i = 0; i < numThreads; ++i )
{
m_Threads.create_thread(
[&]()
{
m_IoService.run();
});
}
Now all threads are dispatching events on the io_service
// Now post your jobs
m_IoService.post(boost::bind(...)); // this will be executed in one of the threads
m_IoService.post(boost::bind(...)); // this will be executed in one of the threads
m_IoService.post(boost::bind(...)); // this will be executed in one of the threads
m_IoService.stop(); // explicitly stop the io_service
// now join all the threads and wait for them to exit
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…