Boost awaitable: how to await on async operation inside post

Viewed 1026

I was writing some asio code and tried to refactor it to use C++20 coroutines. However I got stuck transforming this code:

asio::post(
    my_strand,
    [self = shared_from_this()]() {
        // functions that write in this container can only be called
        // on a single thread at a time, thus the strand
        session_write_history.push_back(buffer);
        /* co_await? */ socket.write_async(buffer, /* use awaitable? */);
    }
);

You see, my async operation is done inside the post callback, so using asio::use_awaitable on the async operation one would make the callback a coroutine. Is there a way to await on the async operation inside the asio::post on the strand?

1 Answers

Simply send asio::use_awaitable instead of a callback to post. This will make your function awaitable. You will then be able to put your async calls directly in your function:

co_await asio::post(my_strand, asio::use_awaitable);
// ...
// code that runs on the strands context
// ...
co_await socket.async_write_some(buffer, asio::use_awaitable);

You can in fact, use asio::use_awaitable in any place where you would put a callback, so transforming callback async code into coroutines can be done pretty much 1:1

Related