Coroutines (C++20)
The new keywords
Keyword | Meaning |
|---|---|
co_await | Suspend execution until the awaited operation completes |
co_yield | Suspend execution and produce a value back to the caller (used for generators) |
co_return | Finish the coroutine, optionally producing a final result |
Using any of these three keywords anywhere in a function's body automatically makes that function a coroutine — the compiler transforms it behind the scenes into a state machine capable of suspending and resuming.
A conceptual generator example
Conceptual sketch of a generator coroutine
// Conceptual only -- Generator<T> is a user- or library-defined type,
// not something the standard library hands you out of the box.
Generator<int> countUpTo(int limit) {
for (int i = 1; i <= limit; ++i) {
co_yield i; // suspend here, hand 'i' back to the caller
}
co_return; // coroutine finished
}
void useGenerator() {
for (int value : countUpTo(5)) {
// Each iteration resumes the coroutine from where it
// last suspended, producing 1, 2, 3, 4, 5 one at a time.
std::cout << value << " ";
}
}A coroutine is a function that can suspend and resume, preserving its local state between suspensions.
co_await suspends on an operation, co_yield suspends while producing a value, co_return ends the coroutine.
Coroutines suit generators, lazy sequences, and asynchronous I/O particularly well.
Raw C++20 coroutines are a low-level toolkit; most developers use them via a library rather than writing the supporting machinery themselves.