H
H
HamsterGamer2022-02-23 00:02:14
ASIO
HamsterGamer, 2022-02-23 00:02:14

Why do we need to wait for an asynchronous operation in this example?

There is the following example from the boost documentation, tell me why this line is used in the receive method?

do io_service_.run_one(); while (ec == boost::asio::error::would_block);

I don't understand what is the point of this idea.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Makarov, 2022-02-23
@Nipheris

In the same example, everything is written, a little higher. I quote:

// Set up the variables that receive the result of the asynchronous
// operation. The error code is set to would_block to signal that the
// operation is incomplete. Asio guarantees that its asynchronous
// operations will never fail with would_block, so any other value in
// ec indicates completion.
ec = boost::asio::error::would_block;
std::size_t length = 0;

Notice the "so any other value in ec indicates completion". We are shown that the initial value ecis set to would_blockand is used as a marker that we have NOT written anything to the ec variable in the handler YET handle_receive. In other words, as a marker of what handle_receivehas not yet been completed. When it is executed, then, according to the Asio interface, something other than would_block, which will be written to ec. This will be the condition for exiting the loop.
The loop here is organized to wait for a particular asynchronous read operation to complete.
It may seem to you that only one asynchronous operation is started here, but this is not so, because there is also a timer firing deadline_. From which it can be concluded that each callrun_oncecan run either the handler handle_receive, or check_deadline(remember that it run_oncepumps only one call to any handler in the queue).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question