kispaljr
kispaljr

Reputation: 2052

Boost Asio: Calling sync read while an async_read is pending on the same socket

I am continuously reading from a socket with async_read(). However on some events I have to send data through the same socket synchronously and wait for an ACK (also synchronously) in an event handler other than the above mentioned async_read's. I am waiting for the ACK in a synchronous read() call. (Please not that I am not talking about async_read_some and read_some).

Is it OK to call a sync read() while an async_read() is pending in the background?

Is it possible that async_read() already received half a message into its internal buffer and my sync read() will return with the second half?

How can I gracefully cancel/suspend async_read() (without any data loss), so I can safely call sync read() in the meantime?

Upvotes: 4

Views: 1478

Answers (1)

Stephan Dollberg
Stephan Dollberg

Reputation: 34518

You may not do that.

Quote from the boost doc:

This operation is implemented in terms of zero or more calls to the stream's async_read_some function, and is known as a composed operation. The program must ensure that the stream performs no other read operations (such as async_read, the stream's async_read_some function, or any other composed operations that perform reads) until this operation completes.

As plain boost::asio::read is also a composed read operation this might invoke UB.

To gracefully stop your async_read you can call cancel(*) nevertheless should think about your design when mixing async and normal operations. I would recommend sending the ACK from the async_read-callback handler.

(*) Note that cancel has some disadvantages, described in the link. One is e.g. that `cancel might be ignored.

Upvotes: 4

Related Questions