51

Can anyone tell me the difference between io_service dispatch and post? It was not clear to me what is more suitable for my problem.

I need to invoke a handler inside another handler and I don't know what invoker to use.

2 Answers 2

54

Well, it depends on the context of the call, i.e. is it run from within the io_service or without:

  • post will not call the function directly, ever, but postpone the call.
  • dispatch will call it rightaway if the dispatch-caller was called from io_service itself, but queue it otherwise.

So, it depends on the function calling post/dispatch was called, and if the given handler can be called straight away or not.

What this means:

... is that dispatch might eventually call your code again (naturally, this depends on your app and how you chain calls), but in general you should make sure your callback is re-entrant if you use dispatch.

dispatch is thus faster, as it avoids queueing the call if possible. It comes with some caveats, so you might want needs to use post occasionally, or always (if you want to play it safe and can afford it).

Update

To incorporate some from @gimpf 's deleted answer, an older boost version had this implementation of dispatch (my comments):

template <typename Handler>
void dispatch(Handler handler)
{
  if (call_stack<win_iocp_io_service>::contains(this)) // called from within io_service?
    boost_asio_handler_invoke_helpers::invoke(handler, &handler); // invoke rightaway
  else
    post(handler); // queue
}
2
  • What do you mean by ~"will not call the function directly, ever? How will the function get called then. Commented Jun 27, 2016 at 16:48
  • 4
    @IgorGanapolsky: By directly I mean as a descendant of the ´post()´ call you make. Instead, it will be called indirectly due to you calling poll() or a similar top-loop method that checks to see if there is any work to be done (calls to be dispatched, timers that have expired or new data on sockets, etc).
    – Macke
    Commented Jun 28, 2016 at 5:47
15

see this blog entry:
To post or to dispatch? - This Thread

Running the application we'll see the difference between posting and dispatching. Since it could do it, dispatch() would execute fB() directly, so we'll see it runs in the current thread, and synchronously. On the other side, post() would ask to io_service to do the job, asynchronously in another thread, and it immediately returns the control to the caller.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.