Search code examples
c++boost-asio

What is the difference between post and dispatch from boost::asio when overloads with executor parameter are used?


I saw several questions like this, regarding post vs dispatch when only handler is passed which is posted on associated executor. I understand that dispatch can invoke synchronous call of handler without queueing it, when current execution is performed on the associated executor. I thought the same principle would be applied to second overload, but it is specifically said in the documentation that The function object is queued for execution, and is never called from the current thread prior to returning from dispatch().

So what is the difference between post and dispatch in this case?


Solution

  • You're linking to old documentation.

    Further, even in that version, the documentation for the non-executor overload said the exact same thing, so the purported difference didn't exist.

    I think it was an oversight¹ in documentation, even then, and current versions make it clear that the handler may be invoked prior to return:

    The function object may be called from the current thread prior to returning from dispatch()

    Side Note

    I'd like to note that invocation can still be optimized even if not invoked before returning from dispatch itself, because

    • the handler maybe pushed to a local queue instead and be executed immediately after returning from a currently executing handler. This may actually be better for allocation/deallocation ordering patterns.
    • the handler may have an associated executor for immediate execution. This is a new feature

    ¹ the fixup was in the commit 0340c15e4 Fix up dispatch() documentation. Clarify distinction between post() and defer(). (Mar 7 2019(