Mar 6, 2023 at 2:57am UTC
I am being confused the asio::timer coroutine does not work if I modify the timer in another coroutine:
The "Leave foo" never reached:
Enter foo
Enter bar
Leave bar
The End
static asio::awaitable<void> foo(asio::steady_timer& timer)
{
cout << "Enter foo" << endl;
timer.expires_from_now(asio::steady_timer::clock_type::duration::max());
co_await timer.async_wait(asio::use_awaitable);
cout << "Leave foo" << endl;
}
static asio::awaitable<void> bar(asio::steady_timer& timer)
{
cout << "Enter bar" << endl;
sleep(2); // wait a little for asio::io_service::run to be executed
timer.expires_after(asio::chrono::seconds(1));
cout << "Leave bar" << endl;
co_return;
}
int main()
{
asio::io_context ioService;
asio::steady_timer timer(ioService);
asio::co_spawn(ioService, foo(timer), asio::detached);
asio::co_spawn(ioService, bar(timer), asio::detached);
ioService.run();
std::printf("The End\n");
return 0;
}
Mar 6, 2023 at 8:02am UTC
I know very little about coroutines so excuse me if I say something stupid, but in foo you set the timer to expire after max duration ? Isn't that a VERY long time? If async_wait will wait until that duration has passed, and there is nothing else that will make it return before that, then it seems to me like it would be stuck there for a very long time.
Mar 6, 2023 at 8:42am UTC
The timer will expire in function bar:
timer.expires_after(asio::chrono::seconds(1));
Yes it will. If I set the timer a callback, it would be executed. But in this case, I set it "asio::use_awaitable", the coroutine will NOT be resumed.