Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Concurrency

Coroutines in practice

Build a working C++20 generator and a lazy task from scratch: promise_type, awaiters, suspension points, lifetime rules and when to use std::generator.

A coroutine is a function that can pause in the middle and be resumed later, keeping its local variables alive in between. C++20 adds three keywords for this: co_yield (produce a value and pause), co_await (pause until something is ready) and co_return (finish with a result). Any function that uses one of them is a coroutine.

The language provides only the machinery. The return type of the coroutine decides what it means, through a nested promise_type that you (or a library such as std::generator) write. This page builds the two most common shapes by hand, a generator and a lazy task, so that the pieces stop being magic. For everyday code you will use std::generator (C++23) instead of writing your own.

C++
Generator<int> count(int n) {
    for (int i = 1; i <= n; ++i) co_yield i;   // pause here, hand out i
}

Try it

C++ A hand-written generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ A lazy task with co_await and co_return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

How it works

When you call a coroutine, the compiler allocates a coroutine frame (usually on the heap) holding the parameters, locals and the suspension state, creates the promise_type object inside it and calls get_return_object() to build what the caller receives. Then, in order:

  1. co_await promise.initial_suspend() decides whether the body starts at once (suspend_never) or the caller gets control first (suspend_always, a "lazy" coroutine).
  2. The body runs. co_yield x means co_await promise.yield_value(x); co_return v calls promise.return_value(v) (or return_void()), then jumps to the end.
  3. At the end co_await promise.final_suspend() runs. Return suspend_always there so the handle stays valid and you can read the result; the frame is destroyed only when someone calls handle.destroy().

Each co_await expr uses an awaiter with three functions: await_ready() (can we skip suspending?), await_suspend(handle) (called after suspension; it may return void, bool or another handle to jump to) and await_resume() (its result is the value of the co_await expression). std::suspend_always and std::suspend_never are the two trivial awaiters.

Usage notes

  • A coroutine is not a thread. Nothing runs in parallel; resume() runs the body on the calling thread until the next suspension point. Threads, event loops or schedulers decide where a coroutine is resumed.
  • Lifetime: the handle owns the frame. Destroy it exactly once (the examples do it in the destructor of a move-only wrapper). Resuming a coroutine that is done() is undefined behavior.
  • Never take parameters by reference if the coroutine may outlive the caller's objects. A lazy coroutine that starts later reads references that may already be dangling; take by value.
  • Exceptions: unhandled_exception() is called inside a catch block for exceptions escaping the body. The examples terminate; real code usually stores std::current_exception() and rethrows from the result accessor.
  • Allocation: each call may allocate the frame. Compilers can elide it when the frame is not escaping, but do not rely on that.
  • Lambdas as coroutines are dangerous when they capture variables: the closure object can be destroyed while the coroutine still uses its captures. Pass data as parameters instead.
  • Use the library: std::generator (C++23, <generator>) gives you a ready generator with range support, recursion and correct lifetimes. Task types and schedulers are not in the standard library yet (C++26 std::execution is only starting).
  • Debugging: locals live in the frame, so a debugger shows them only while the coroutine is suspended or running.