ASIO IO completion callbacks order vs the order of actual IO operations

bobah

It is obvious from the implementation that IO completion callbacks are invoked in the same order as the actual IO operations when running in a single thread mode, but I cannot find the respective part of the documentation confirming that. Is it written explicitly anywhere?

Richard Hodges

The documentation of all of the async_xxx methods on io-object classes have a passage like this:

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Looking at the documentation of boost::asio::io_service::post()...

This function is used to ask the io_service to execute the given handler, but without allowing the io_service to call the handler from inside this function.

The io_service guarantees that the handler will only be called in a thread in which the run(), run_one(), poll() or poll_one() member functions is currently being invoked.

And that is the full extent of your guarantee.

If your code relies on the temporal ordering of asynchronous events, then it is not asynchronous code.

Even the documentation of run_one() make no guarantees about which handler it will dispatch:

The run_one() function blocks until one handler has been dispatched, or until the io_service has been stopped.

If you must sequence individual async operations (such as reads), then you are obliged to either:

  • initiate the second operation from the handler of the first, or

  • keep a flag set while an operations' handler is outstanding, and only initiate another operation when the flag is false.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related