The example code tends to focus much more on demonstrating strand
as a synchronization mechanism, rather than providing a solution for the producer-consumer problem.
For a motivational case of using strand
to solve a producer-consumer problem, consider a GUI based chat client using TCP. The GUI can produce multiple messages, trying to send a message before the previous message has been written to the connection. Meanwhile, the application needs to consume and write each message to the TCP connection while preserving the messages, resulting in no interleaving data. Composed operations, such as async_write
, requires that the stream perform no other write operations until the composed operation completes. To account for these behaviors:
- A queue can buffer chat messages.
- The GUI can post an operation into
strand
that will:- Add the chat message to the queue.
- Conditionally start the consumer.
- The consumer is an asynchronous call-chain that reads from the queue and writes to the socket within the
strand
.
See this answer for an implementation.