Boost Asio: call sync to read when async_read is pending on the same socket

I am continuously reading from a socket with async_read()

. However, in some cases, I have to send data over the same socket synchronously and wait for an ACK (also synchronously) in an event handler other than the above async_read

. I am waiting for ACK in a synchronous call read()

. (Please don't say that I'm not talking about async_read_some

and read_some

).

Can sync be triggered read()

while async_read()

idle in the background?

Is it possible that I async_read()

have already received half of the message in my internal buffer and my sync read()

will come back with the second half?

How can I undo / pause gracefully async_read()

(no data loss) so I can safely call sync read()

in the meantime?

+3


source to share


1 answer


You cannot do this.

Quoting from boost file:

This operation is performed in terms of zero or more calls to the thread's async_read_some function and is known as a stacked operation. The program must ensure that the thread does not perform any other read operations (such as async_read, the thread's async_read_some function, or any other configured read operations) until that operation completes.



Since simple is boost::asio::read

also a compound read operation, it can call UB.

To gracefully stop yours async_read

, you can call cancel

(*), however, you should think about your design when mixing asynchronous and normal operations.I would recommend sending an ACK from the async_read

-callback handler .

(*) Please note that cancellation has some disadvantages described in the link. One of them, for example, is that `cancel can be ignored.

+3


source







All Articles