Boost :: asio socket async_ * strand

How to perform async_ * operations on a socket through a chain? I looked at Timer.5 (Boost / Asio examples), but they only show how to call the user exit. When I async_write to a socket in multi-threaded applications, the data may get corrupted. And strand ensures that none of these handlers will be executed at the same time.

+8
boost asynchronous sockets boost-asio
source share
2 answers

From Boost.Asio docs:

The io_service :: strand class provides the ability to send and send messages to handlers with the guarantee that none of these handlers will execute at the same time.

There is a good example of using strand in Boost.Asio examples .

strand ensures that the execution of your handler is synchronized. This means strand is useful if your io_service is running from multiple threads. This is not related to how you plan your tasks (handlers).

strand cannot help you perform multiple read or write operations of a socket at the same time, because internal read / write cannot be performed at the same time, so there should only be one active read or write async op.

For reads you simply call async_read to initiate the read sequence and call it again from the read handler after consuming the received data. The same thing you do in a single-threaded environment.

For writes , if there are parallel producers (if several threads provide data for writing to the socket), you need a parallel queue (for example, increase the circular buffer , find the "Bounded Buffer Example"). Your write function receives data from this buffer, and async writes it to the socket. Your write handler calls your write function.

+4
source share

When I async_write() in a socket in a multi-threaded application data can be damaged. And Strand ensures that none of these handlers will execute at the same time.

If multiple streams require writing data to a socket, you will need to ensure data is streamlined. This is clearly seen in the async_write() documentation .

The program must ensure that the thread does not write any other operations (such as the async_write, the async_write_some function stream, or any other composed operations that write) until this operation completes.

I propose supporting an outgoing message queue that is very similar to this question and my answer .

+3
source share

All Articles