Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::asio socket async_* strand

How to perform async_* operations on socket through the strand? I've looked at Timer.5 (Boost/Asio examples), but they only show how to invoke user's handler. When I async_write to the socket in multithreaded application data may be written corrupted. And a strand guarantees that none of those handlers will execute concurrently.

like image 445
user869217 Avatar asked Jul 29 '11 10:07

user869217


1 Answers

From Boost.Asio docs:

The io_service::strand class provides the ability to post and dispatch handlers with the guarantee that none of those handlers will execute concurrently.

There's a good example of strand usage in Boost.Asio examples.

strand guarantees that your handler execution will be synchronized. That means that strand is useful if your io_service is executed from multiple threads. It's not related to how you schedule your tasks (handlers).

strand cannot help you to do multiple socket read or write ops concurrently, because internal read/write execution cannot be done concurrently, so there should be just one active read or write async op.

For reads you just call async_read to initiate read sequence and call it again from your read handler after consuming received data. The same that you do in single threaded environment.

For writes if there're concurrent producers (if multiple threads provides data to be written to socket) you need a concurrent queue (e.g. boost circular buffer, look for "Bounded Buffer Example"). Your write function takes data from this buffer and async writes it to socket. Your write handler invokes your write function.

like image 129
Andriy Tylychko Avatar answered Oct 02 '22 21:10

Andriy Tylychko