Invoking a write operation on a stream that has an outstanding async_write()
operation fails to meet a requirement of async_write()
, which can result in interwoven data. Additionally, if multiple threads are servicing the io_service
event loop or Session::do_write()
is invoked from a thread that is not processing the event loop, then the use of a mutex will fail to meet the thread safety requirement of the stream. This answer demonstrates using a queue to serialize multiple async_write()
operations, and processing the queue with an asynchronous call chain within a strand
, fulfilling both the requirements of async_write()
and the stream's thread safety.
For further details, the async_write()
function is a composed operations, resulting in zero or more calls to the stream's async_write_some()
function. Therefore, if the program does not ensure that the stream performs no other write operations until the outstanding operation completes, the intermediate write operations can be mixed between other write operations, resulting in interwoven data. Furthermore, these intermediate operations invoke async_write_some()
on the stream without having acquired doWrite_mutex
, potentially violating the thread safety requirement for the stream. For more information about composed operations and strand
usage, consider reading this answer.