chriskohlhoff / asio

Asio C++ Library
http://think-async.com/Asio
4.72k stars 1.19k forks source link

A question regarding awaitables and executors #1459

Open assafcohen opened 2 months ago

assafcohen commented 2 months ago

Hi, I have a question regarding the following code:

#include <boost/asio.hpp>

boost::asio::awaitable<void> sleepFor1(const auto& duration)
{
    boost::asio::steady_timer timer(co_await boost::asio::this_coro::executor);
    timer.expires_after(duration);
    co_await timer.async_wait(boost::asio::use_awaitable);
}

auto sleepFor2(const auto& duration, auto&& exec)
{
    boost::asio::steady_timer timer(exec);
    timer.expires_after(duration);
    return timer.async_wait(boost::asio::use_awaitable);
}

int main(int argc, char* argv[])
{
    try
    {
        boost::asio::io_context ioc;
        boost::asio::co_spawn(
            ioc,
            []() -> boost::asio::awaitable<void>
            {
                co_await sleepFor1(std::chrono::seconds { 1 }); // succeeds
                co_await sleepFor2(std::chrono::seconds { 2 }, co_await boost::asio::this_coro::executor); // fails
            },
            [](const std::exception_ptr& ptr) {});
        ioc.run();
    }
    catch (std::exception& e)
    {
    }
}

while co_awaiting on : co_await sleepFor1(std::chrono::seconds { 1 }); succeeds co_awaiting on : co_await sleepFor2(std::chrono::seconds { 2 }, co_await boost::asio::this_coro::executor); // fails

since both sleepFor operations returns an awaitable, I thought that both strategies are interchangeable.

What I don't understand?