I've read that multiple operations on sockets from different threads are not recommended. But what if I call from the same thread socket.async_read and next socket.async_write (without waiting for the previous to finish)? Can I expetct that proper callback will run when one of this operations is completed?
The async_write function is a composed asynchronous operation that writes a certain amount of data to a stream before completion. Start an asynchronous operation to write all of the supplied data to a stream.
The async_read function is a composed asynchronous operation that reads a certain amount of data from a stream before completion. Start an asynchronous operation to read a certain amount of data from a stream.
If that is not safe, then only way is probably to get the socket native handle and use synchronous linux mechanisms to achieve concurrent read and writes. I have an application where the reads and writes are actually independent. It is thread-safe for the use-cases you listed. You can read in one thread, and write in another.
I've found that yes, you can have a single pending async_read
and a single pending async_write
on the same socket without an issue. When you call the io_service::run()
method, the callbacks will complete as expected.
Issuing multiple async_reads on the same socket, or multiple async_writes on the same socket, can result in unexpected behavior, depending on the type of socket involved. In particular, using multiple async_writes on the same TCP socket can result in data going out in a different order than you originally expected, and intermixing of data sends. In UDP, it might be more reasonable, but I would still recommend against it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With