2

I was reading the blog about boost asio, (source code) and noticed the following code.

auto timer = net::high_resolution_timer(co_await net::this_coro::executor);

It is not clear to me why timer is constructed using co_await in argument since most of the time I saw co_await used before some called function, not when providing an argument to constructor.

I have checked the boost docs, but there seems to be nothing too notable about timer constuctors, they take executor as argument, but still not clear to me why co_await is needed.

Full function code is this:

net::awaitable<void>
test_widget::run_demo()
{
    using namespace std::literals;

    auto timer = net::high_resolution_timer(co_await net::this_coro::executor);

    for (int i = 0; i < 10; ++i)
    {
        timer.expires_after(1s);
        co_await timer.async_wait(net::use_awaitable);
        this->setText(QString::fromStdString(std::to_string(i + 1) + " seconds"));
    }
    co_return;
}
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
  • 1
    [`net::this_core::executor`](https://www.boost.org/doc/libs/1_74_0/doc/html/boost_asio/reference/this_coro__executor.html) is an awaitable object, hence the `co_await`. – Holt Dec 04 '20 at 14:11
  • this may be related to this https://stackoverflow.com/questions/65821773/what-is-the-implement-of-asiothis-coroexecutor – AndrewBloom Feb 11 '21 at 13:21

0 Answers0