Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost.asio: can I do async_read and async_write simultaneously from one thread?

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?

like image 446
peper0 Avatar asked Nov 29 '12 16:11

peper0


People also ask

What is the async_write() function?

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.

What is the async_read function in JavaScript?

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.

Is it possible to read and write in multiple threads?

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.


1 Answers

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.

like image 158
Dave S Avatar answered Sep 27 '22 16:09

Dave S