c++-coroutine

C++20 co_await sleep?


With C++20 coroutines, as a toy example, I thought it would be easy to make a coroutine that returns a task<T> that co_awaits a sleep before co_returning. It looks like Folly can do it?: https://blog.the-pans.com/build-folly-coro/ but maybe cppcoro doesn't?

I realize C++20 coroutines are a raw compiler feature with no standard libraries yet. Does cppcoro support an awaitable sleep? If not, are there other libraries (or is there a one-pager) that I can play with on Compiler Explorer?


Solution

  • Use boost::asio::deadline_timer.

    A rough toy example:

    boost::asio:io_context ioc;
    
    // You should run ioc in a thread
    
    boost::asio::deadline_timer t(ioc);
    t.expires_from_now(boost::posix_time::seconds(1));
    co_await t.async_wait(asio::use_awaitable); // This will not block the thread.