Skip to content

Avoid async scope lockup #1909

@maxbachmann

Description

@maxbachmann
exec::task<void> test(asio::io_context &ioContext)
{
    asio::steady_timer timer(ioContext);
    timer.expires_after(std::chrono::seconds(10));
    auto [error] = co_await timer.async_wait(asio::as_tuple(exec::asio::use_sender));
}

exec::task<void> test2(exec::async_scope& scope, asio::io_context &ioContext)
{
#if 1
    co_await exec::reschedule_coroutine_on(stdexec::inline_scheduler{});
    co_await scope.nest(test(ioContext));
#elif 0
    co_await stdexec::on(stdexec::inline_scheduler{}, scope.nest(test(ioContext)));
#elif 0
    co_await scope.nest(stdexec::on(stdexec::inline_scheduler{}, test(ioContext)));
#endif
}

exec::task<void> test3(exec::async_scope& scope, asio::io_context &ioContext)
{
    co_await test2(scope, ioContext);
}

    asio::io_context ioContext;
    MyThread recvThread;
    std::optional<exec::async_scope> asyncScope;
    asyncScope.emplace();
    exec::static_thread_pool ctx{1};

    asio::executor_work_guard<asio::io_context::executor_type> workGuard(
        asio::make_work_guard(ioContext));

    recvThread.start([&]
        {
            ioContext.run();
            printf("test\n");
        }, "client_network_thread");


    exec::start_detached(stdexec::starts_on(MainThreadScheduler(), test3(*asyncScope, ioContext)));
    Scheduler::getSingleton()->run(GetTicks());

    sleep(5);
    workGuard.reset();

    asyncScope->request_stop();
    recvThread.join();
    asyncScope.emplace();

What I am attempting to do is to wrap an async function in an async scope t make it cancellable.
In this example the MainThreadScheduler only schedules one initial time so it is expected that it will never fully finish the test3 task.

However I would still like to successfully cancel it. In the test2 function the first case works as expected. Both case 2 and 3 assert inside the asyncScope destructor since the work isn't considered finished. It wasn't fully clear to me why the work isn't considered finished in these cases. Especially in case 2.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions