C++20 Syntax
This page teaches you to read and write a coroutine: the three keywords, a first coroutine, and the awaiter protocol that drives co_await.
The Three Keywords
A function becomes a coroutine when its body contains co_await, co_yield, or co_return, signaling to the compiler that it requires coroutine machinery.
co_await
The co_await keyword awaits an operation and may suspend the coroutine until that operation completes. When you write co_await expr, the coroutine saves its state, pauses execution, and potentially allows other code to run. When the awaited operation completes, the coroutine resumes from exactly where it left off.
capy::task<std::string> fetch_page(std::string url)
{
auto response = co_await http_get(url); // suspends until HTTP completes
co_return response.body; // continues after resumption
}
The return type capy::task is Capy’s lazy coroutine type, which produces a result when awaited.
co_yield
The co_yield keyword produces a value and hands it to the promise. co_yield e means co_await promise.yield_value(e), so the coroutine suspends only if the awaiter that yield_value returns does. This pattern creates generators: functions that produce sequences of values one at a time. A typical generator suspends after each value and pauses until someone asks for the next one.
generator<int> count_to(int n)
{
for (int i = 1; i <= n; ++i)
{
co_yield i; // produce value, suspend, resume when next value requested
}
}
co_return
The co_return keyword completes the coroutine and optionally provides a final result. Unlike a regular return statement, co_return interacts with the coroutine machinery to properly finalize the coroutine’s state.
capy::task<int> compute()
{
int result = 42;
co_return result; // completes the coroutine with value 42
}
For coroutines that do not return a value, use co_return; without an argument.
Your First Coroutine
The distinction between regular functions and coroutines matters because they behave fundamentally differently at runtime:
-
A regular function allocates its local variables on the stack. When it returns, those variables are gone.
-
A coroutine allocates its local variables in a coroutine frame, typically on the heap. When it suspends, those variables persist. When it resumes, they are still there.
#include <coroutine>
struct SimpleCoroutine
{
struct promise_type
{
SimpleCoroutine get_return_object() { return {}; }
std::suspend_never initial_suspend() { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
};
SimpleCoroutine my_first_coroutine()
{
co_return; // This makes it a coroutine
}
The promise_type nested structure provides the minimum scaffolding the compiler needs. Coroutine Machinery explains what each method does.
The presence of co_return transforms what looks like a regular function into a coroutine.
Awaitables and Awaiters
When you see expression co_await aw, the sub-expression aw is an awaitable.
The awaitable names the operation, but it does not decide how the coroutine suspends.
When expression co_await aw is evaluated, the compiler first uses aw to produce an awaiter.
If the promise type has a member await_transform, the compiler calls promise.await_transform(aw) and uses its result.
Otherwise it uses aw itself.
The co_await expressions that the compiler generates for initial suspend, final suspend, and co_yield skip this step.
Next, overload resolution looks for an operator co_await, member or non-member, that accepts that result.
If it finds one, its return value is the awaiter.
Otherwise the result itself is the awaiter.
The awaiter controls suspension and resumption through three member functions:
-
await_ready()— Returnstrueif the result is immediately available and no suspension is needed. -
await_suspend(handle)— Called when the coroutine suspends; receives a handle to the coroutine for later resumption. -
await_resume()— Called when the coroutine resumes; its return value becomes the value of theco_awaitexpression.
Often the awaiter and the awaitable are the same object, as in the example below.
A promise’s await_transform can even make a plain int awaitable.
|
Example: Understanding the Awaiter Protocol
#include <coroutine>
#include <iostream>
struct ReturnObject
{
struct promise_type
{
ReturnObject get_return_object() { return {}; }
std::suspend_never initial_suspend() { return {}; }
std::suspend_never final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() {}
};
};
struct Awaiter
{
std::coroutine_handle<>* handle_out;
bool await_ready() { return false; } // always suspend
void await_suspend(std::coroutine_handle<> h)
{
*handle_out = h; // store handle for later resumption
}
void await_resume() {} // nothing to return
};
ReturnObject counter(std::coroutine_handle<>* handle)
{
Awaiter awaiter{handle};
for (unsigned i = 0; ; ++i)
{
std::cout << "counter: " << i << std::endl;
co_await awaiter;
}
}
int main()
{
std::coroutine_handle<> h;
counter(&h);
for (int i = 0; i < 3; ++i)
{
std::cout << "main: resuming" << std::endl;
h();
}
h.destroy();
}
Output:
counter: 0
main: resuming
counter: 1
main: resuming
counter: 2
main: resuming
counter: 3
Study this execution flow:
-
maincallscounter, passing the address of a coroutine handle -
counterbegins executing, prints "counter: 0", and reachesco_await awaiter -
await_ready()returnsfalse, so suspension proceeds -
await_suspendreceives a handle to the suspended coroutine and stores it inmain’s variable `h -
Control returns to
main, which now holds a handle to the suspended coroutine -
maincallsh(), which resumes the coroutine -
The coroutine continues from where it left off, increments
i, prints "counter: 1", and suspends again -
This cycle repeats until
maindestroys the coroutine
The variable i inside counter maintains its value across all these suspension and resumption cycles.
Only a coroutine can evaluate a co_await expression.
The awaiter, however, is an ordinary object: it need not be a coroutine, or invoke one.
|
Standard Awaiters
The C++ standard library provides two predefined awaiters:
-
std::suspend_always—await_ready()returnsfalse(always suspend) -
std::suspend_never—await_ready()returnstrue(never suspend)
// suspend_always causes suspension at this point
co_await std::suspend_always{};
// suspend_never continues immediately without suspending
co_await std::suspend_never{};