Marius Herzog
Marius Herzog

Reputation: 597

io_service::run() processing order of async_* functions

Suppose when calling io_service::run(), there are multiple async_read operations scheduled (There may be other operations in between them). What happens when an asynchronous operation like async_write is scheduled in the ReadHandler-function?

void handler(const boost::system::error_code& error, std::size_t bytes) {
    async_write(sock, boost::asio::buffer(wbuf), whandler);
}

That is, when will the async_write be invoked? I would expect the order of execution to be:

1) async_read //1
2) async_write
3) async_read //2
4) async_write

Is this order of execution guaranteed?

Upvotes: 5

Views: 324

Answers (3)

Stephan Dollberg
Stephan Dollberg

Reputation: 34558

You are misusing the boost::asio interface.

There may not be more than one pending read operations on a single socket.

Quote from the boost::asio::async_read docs:

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.

Upvotes: 3

sehe
sehe

Reputation: 393134

You can force the order of execution using strands

An excellent description is here: Why do I need strand per connection when using boost::asio?

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249293

No, it's not guaranteed. For example, if the first handler is invoked and wants to write, what if the second buffer is not yet available to read? Of course the write should come first. But what if the write is not possible by the time the second buffer is ready to read? Then of course the second read should occur before the first write.

Upvotes: 4

Related Questions