Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost asio io_service dispatch vs post

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.

like image 930
coelhudo Avatar asked Feb 24 '10 14:02

coelhudo


People also ask

Is boost asio post thread safe?

Thread Safety In general, it is safe to make concurrent use of distinct objects, but unsafe to make concurrent use of a single object. However, types such as io_service provide a stronger guarantee that it is safe to use a single object concurrently.

What is boost io_service?

The io_service class provides the core I/O functionality for users of the asynchronous I/O objects, including: boost::asio::ip::tcp::socket. boost::asio::ip::tcp::acceptor. boost::asio::ip::udp::socket. deadline_timer .

Does boost asio use Epoll?

For me, main advantage of Boost. Asio (besides cross-platform work) is, that on each platform, it uses most effective strategy ( epoll on Linux 2.6, kqueue on FreeBSD/MacOSX, Overlapped IO on MS Windows).

What is asio post?

boost::asio::post posts a given functor into the execution queue and that functor is executed along with other functors and completion handlers in a general way. The function is thread-safe so feel free to post from different threads.


1 Answers

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 } 
like image 88
Macke Avatar answered Sep 20 '22 22:09

Macke