Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::asio::io_service - why use post function?

Tags:

c++

boost

I'd like for someone to tell me the pros (and cons) for using the post function. Why and when should I prefer using post and why/when should I not want to use it?

like image 496
eve Avatar asked Jul 31 '11 10:07

eve


People also ask

What is boost asio post?

boost::asio::post takes any callable object. Requirements for such object you can find here. There are many ways to achive what you want: [1] lambda expressions boost::asio::post(tp, [i]{ printProduct(i); });

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.

How does boost asio work?

At its core, Boost Asio provides a task execution framework that you can use to perform operations of any kind. You create your tasks as function objects and post them to a task queue maintained by Boost Asio. You enlist one or more threads to pick these tasks (function objects) and invoke them.

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).


2 Answers

Post is very useful when you want the callback to occur essentially now, but not in the current context. Reasons might include:

  • The current context is holding locks and you want the function to be called after they have been released. This would allow the function to acquire those locks itself without causing a deadlock.

  • The call stack might be very deep

  • The current thread might be inappropriate for the function in some other way, and post is a convenient way of scheduling the function in another thread.

like image 178
janm Avatar answered Sep 24 '22 13:09

janm


I'm guessing you're comparing post() to dispatch(). In general, post() is safer, because dispatch() may call the handler right away, and there is a risk in event-driven programming that you affect queued events in unexpected ways. Also there is merit in keeping the call stack small, and in having more predictable behavior (dispatch() may run now or may run later).

I just found post() useful for deleting an object only after the current io_service event/handler/operation finishes.

like image 42
Peter Tseng Avatar answered Sep 23 '22 13:09

Peter Tseng