What is the difference between post and dispatch in boost::asio?
Asked Answered
W

2

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 ?

Wiser answered 18/6, 2018 at 14:3 Comment(0)
K
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.

Kingcup answered 18/6, 2018 at 14:8 Comment(2)
What determines if the"potential" aspect is realized?Monobasic
@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.Kingcup
C
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.

Canopus answered 18/6, 2018 at 14:6 Comment(3)
may or is guarenteed to?Monobasic
@ChristopherPisz may. It only promises that it will be run on a thread that called run(), run_one(), poll() or poll_one()Canopus
@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.Hotel

© 2022 - 2024 — McMap. All rights reserved.