c++boostboost-asio

In Asio, can completion handlers of async_XX operation be called before the calling thread returns


I am calling async_write from the context thread (event loop thread that is associated with boost context). For my code to operate correctly, it is important that the completion handler (with or without errors) be called only after the async_write returns.

According to the documentation:

If an asynchonous operation completes immediately (that is, within the thread of execution calling the initiating function, and before the initiating function returns), the completion handler shall be submitted for execution as if by performing ex2.post(std::move(f), alloc2). Otherwise, the completion handler shall be submitted for execution as if by performing ex2.dispatch(std::move(f), alloc2).

However it not not still clear to me if completion the handler can be called before the async_write returns as I could not find the difference between post and dispatch.


Solution

  • Post never immediately invokes the handler.

    Dispatch might immediately invoke the handler if allowed (the executor matches the running thread).

    The distinction is made to uphold the ordering guarantees, including order of (de)allocations involved in the async operation(s).

    TL;DR Your requirements are already guaranteed by all Asio async initiation functions.

    Side Note:

    Asio 1.27.0 (Boost 1.83) added the ability to customise the execution of a completion handler when an operation completes immediately.. This means that if you insist on the opposite behavior, you now can: Customizing Immediate Completion. That documentation page might also reinforce your understanding of the default behavior.