boost asio io_service.run()
I was just going over the asio chat server example. My question is about their usage of the io_service.run()
function. The documentation for the io_service.run()
function says:
The run() function blocks until all work has finished and there are no m开发者_如何学运维ore handlers to be dispatched, or until the io_service has been stopped. Multiple threads may call the run() function to set up a pool of threads from which the io_service may execute handlers. All threads that are waiting in the pool are equivalent and the io_service may choose any one of them to invoke a handler. The run() function may be safely called again once it has completed only after a call to reset().
It says that the run function will return, and I'm assuming that when it does return the network thread stops until it is called again. If that is true, then why isn't the run function called in a loop, or at least given its own thread? the io_service.run()
function is pretty much a mystery to me.
"until all work has finished and there are no more handlers to be dispatched, or until the io_service has been stopped"
Notice that you DO install a handler, named handle_accept
, that reinstalls itself at each execution. Hence, the io_service.run
will never return, at least until you quit it manually.
Basically, at the moment you run io_service.run in a thread, io_services proactor takes over program flow, using the handler's you installed. From that point on, you handle the program based on events (like the handle_accept
) instead of normal procedural program flow. The loop you're mentioning is somewhere deep in the scary depths of the asio's proactor ;-).
精彩评论