提升等待:如何等待帖子内的异步操作

Gui*_*cot 5 c++ boost-asio c++20 c++-coroutine

我正在编写一些 asio 代码并尝试重构它以使用 C++20 协程。然而我在转换这段代码时遇到了困难:

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? */);
    }
);
Run Code Online (Sandbox Code Playgroud)

您会看到,我的异步操作是在后回调内完成的,因此asio::use_awaitable在异步操作上使用将使回调成为一个协程。有没有办法等待asio::post链上的异步操作?

Gui*_*cot 6

只需发送asio::use_awaitable而不是回调即可发布。这将使您的函数等待。然后,您将能够将异步调用直接放入您的函数中:

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);
Run Code Online (Sandbox Code Playgroud)

事实上,您可以asio::use_awaitable在任何需要放置回调的地方使用,因此将回调异步代码转换为协程几乎可以 1:1 完成