7

I am trying to use boost:asio library to create a threadpool. The official documentation says :

dispatch : Request the io_service to invoke the given handler.

post: Request the io_service to invoke the given handler and return immediately.

Could someone explain how these two differ ?

Community
  • 1
  • 1

2 Answers2

4

The difference is dispatch may run handler (the CompletionHandler passed to it) inside it which means you will wait for it to finish, if it does, before the function returns. post on the other hand will not run handler itself and returns back to the call site immediately.

So, dispatch is a potentially blocking call while post is a non-blocking call.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • What determines if the"potential" aspect is realized? – Christopher Pisz Jun 18 '18 at 15:23
  • 1
    @ChristopherPisz If `dispatch` can grantee 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* then it may make it a blocking call. – NathanOliver Jun 18 '18 at 15:25
2

Post ensures that the thread that calls post will not immediately attempt to process the task.

https://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/reference/io_service/post.html

but without allowing the io_service to call the handler from inside this function.

Dispatch makes no such promise; and may be completed by the time the function returns.

UKMonkey
  • 6,941
  • 3
  • 21
  • 30
  • may or is guarenteed to? – Christopher Pisz Jun 18 '18 at 15:22
  • @ChristopherPisz may. It only promises that it will be run on a thread that called `run(), run_one(), poll() or poll_one()` – UKMonkey Jun 18 '18 at 15:35
  • @ChristopherPisz If `dispatch()`ing a job to a strand (or any other single-execution object), that is already busy (i.e. running some other completion handler), then `dispatch()` will behave like `post()` and mark the job for later execution. – Kai Petzke Apr 03 '21 at 16:36