c++ – asio: asio::awaitable yield execution to other ready tasks
Consider the code
#include
asio::awaitable doit(char ch)
{
for (int i = 0; i < 5; ++i) {
fprintf(stderr, "%c %d\n", ch, i);
asio::steady_timer t(co_await asio::this_coro::executor);
t.expires_after(std::chrono::seconds(0));
co_await t.async_wait(asio::use_awaitable);
}
}
int main()
{
asio::io_context ctx;
co_spawn(ctx, doit('A'), asio::detached);
co_spawn(ctx, doit('B'), asio::detached);
ctx.run();
return 0;
}
Which produces the following output:
A 0
B 0
A 1
B 1
A 2
B 2
A 3
B 3
A 4
B 4
This does exactly what I want, but with the hack of steady_timer expiring after “0” seconds.
In my application I want a long running tasks (a few ms) to yield execution at multiple points and give a change of pending tasks in the io_context to run.
Is there a more idiomatic approach than this steady_timer hack?
Read more here: Source link
