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