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?
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); });
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With