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 writ开发者_开发技巧ten 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.
When I
async_write()
to the socket in multithreaded application data may be written corrupted. And Strand guarantee that none of those handlers will execute concurrently.
If multiple threads need to write data on the socket, you will have to ensure ordering of the data. This is explicitly clear in the async_write()
documentation.
The program must ensure that the stream performs no other write operations (such as async_write, the stream's async_write_some function, or any other composed operations that perform writes) until this operation completes.
I suggest maintain an outgoing queue of messages, which is very similar to this question and my answer.
精彩评论