Thread safe full duplex sockets
This question has been asked many times, but I'm still not satisfied with the answers. I want to use a socket in full duplex: 1. asynchronously: with async_read, async_write (multiple threads running io_service.run()) 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. Please refere to any official documents of boost. -- View this message in context: http://boost.2283326.n4.nabble.com/Thread-safe-full-duplex-sockets-tp4691552... Sent from the Boost - Users mailing list archive at Nabble.com.
On 8/02/2017 22:41, Christi258 wrote:
This question has been asked many times, but I'm still not satisfied with the answers. I want to use a socket in full duplex: 1. asynchronously: with async_read, async_write (multiple threads running io_service.run()) 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 triggered elsewhere.) Also, strongly consider using async with coroutines (which highly resembles sync code) instead of using actual sync code -- it scales a lot better. 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).
participants (2)
-
Christi258
-
Gavin Lambert