r/cpp • • 3d ago

Bottom Up Coroutines in C++

https://forcedrift.github.io/roshaniruku/posts/bottom-up-coroutines-in-cpp/
61 Upvotes

5 comments sorted by

4

u/grishavanika 3d ago

Since Task<> owns coroutine - i.e., destroys coroutine on scope exit - future_.then() is not safe (see Resuming the coroutine when the future completes):

std::coroutine_handle<> await_suspend(
    std::coroutine_handle<> handle
) {
    handle_ = handle;

    future_.then(
        [this](Future<T>&&) {
            auto previous = status_.exchange(
                kCallbackDone,
                std::memory_order_acq_rel
            );

            if (previous == kSuspended) {
                handle_.resume();
            }
        },
        kImmediateInvoker
    );

since it captures this which is destroyed when Task<> goes out of scope. From current code, everything seems to be sync_wait()-ed, hence Task is never destroyed while awaiting. If I'm reading right, proposed spawn_on starts the Task, so this crashes:

Task<int> calculate()
{
    dispenso::Future<int> future = start_async_operation();
    int result = co_await future;
    co_return result;
}

Task<void> start()
{
    return co_await calculate();
}
// 
{
    Task<void> a = spawn_on(start())	
} // destroy a

2

u/Ezmanz 2d ago

Thank you for pointing this out; I really appreciate the feedback, and I overlooked this part. Currently the status handshake only prevents a double resume, not frame lifetime. I will add a fix for this in the blog.

For the current API/blog examples, this isn’t reachable, since Task is lazy and every start path (sync_wait, co_await, detach) keeps the frame alive until completion. However, this change would be necessary for implementing spawn_on.

I will update the blog to call this out and fix the design before adding spawn_on. The fix will change ownership of the spawned frame, not just the handle type returned. Will most likely either return a shared handle / Future<T> where the runtime owns and keeps the coroutine frame alive until completion, or add cancellation with safe unregistration and deferred frame destruction.

2

u/grishavanika 2d ago

regarding spawn_on design - people usually have a separate Task type for an eager (i.e., non lazy coroutine). I would not make it start a task since then you have unnecesary race condition you need to handle when implementing algorithms on top of it, e.g., when_all must take into account the state/in-progress/completed task. If spawn_on is lazy, when_all is simpler to implement, assumes all the tasks are suspended, consumes them:

  1. prepare the state, subscribe to Tasks continuation/end
  2. resume all of the tasks - i.e., run concurrently

but I may miss the ideas around the library, its Future type - for instance, you want to spawn_on/launch as soon as possible, without delaying to when_all, etc etc (still, delaying to when_all allows to spawn N tasks in batches and so on)

2

u/leirus 13h ago

I like how you admit that coroutines are a hard concept to grasp in C++. Sometimes I was afraid it's only me going crazy :D