In this boost asio example why is the io_service started after .async_accept is called

StackOverflow https://stackoverflow.com/questions/21089391

  •  27-09-2022
  •  | 
  •  

Question

question is simple(my boost asio knowledge is really bad, so it is probably trivial):
http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/tutorial/tutdaytime3/src.html

Why is io_service started after we already executed ctor that does async_accept ?

Was it helpful?

Solution 2

Because that's the most convenient way to write this code. There's no harm in starting asyncronous operations before their completion can be handled, as long as they are handled at some point. If they complete before the service starts, then they are queued until it does.

The constructor could dispatch the start_accept function to the io_service if you really wanted to defer it until the service is running, but that would just add extra complication, and a delay, for no benefit.

OTHER TIPS

The io_service::run() function blocks until all work has finished and there are no more handlers to be dispatched. If io_service::run() has nothing to do it returns immediately. So you need to provide some work before starting. Like it does in boost example:

{
    boost::asio::io_service io_service;
    tcp_server server(io_service);   // <-- prepares async task
    io_service.run(); // <-- blocks 
} // <-- all done 

Ok, lets try to call run before tcp_server instantiation

{
    boost::asio::io_service io_service;
    io_service.run(); // <-- returns immediately
    tcp_server server(io_service);   // <-- prepares async task
} // <-- async task is cancelled (or its result is lost)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top