Post by Christi258
This question has been asked many times, but I'm still not satisfied with the
1. asynchronously: with async_read, async_write (multiple threads running
2. synchronously: with read and write in two distinct threads
I am pretty sure that 1. is thread safe using strands.
But I can find no information about 2.
ASIO makes no specific guarantees AFAIK, it's down to your OS. But in
general sockets are safe to read and write on separate threads as long
as you only have one concurrent read and one concurrent write. This is
also the case with serial ports, but not the case with files.
(The standard pattern is to have reading in an implicit strand by
kicking off an initial read on connection and subsequent reads whenever
the first read completes, and then to do writes either with an explicit
strand or with an application layer that guarantees it won't issue
concurrent writes. Depending on your protocol and application structure
writes might be triggered from the read handlers or they might be
Also, strongly consider using async with coroutines (which highly
resembles sync code) instead of using actual sync code -- it scales a
Where you have to be a bit more careful with multiple threads are
operations that mutate the state of the socket itself -- in particular
if something closes the socket (typically in response to an error).
Closing the socket on one thread should result in aborting any pending
operations on the other threads, but you need to be careful to not start
new operations (since clearing the OS handle might not have propagated
to the other thread yet, and the OS might have reused the handle id for
some other connection in the meantime).