Introduction To C++20 Coroutines
Every C++ function you have ever written follows the same contract: it runs from start to finish, then returns. The stack frame lives and dies in lockstep with that single invocation. But it forces a hard tradeoff when programs need to wait—for a network response, a disk read, a timer, or another thread. The function either blocks (wasting a thread) or you restructure your code into callbacks, state machines, or futures that scatter your logic across multiple places.
A coroutine can suspend its execution—saving its local state somewhere outside the stack—and resume later, picking up exactly where it left off. The control flow reads top-to-bottom, like the synchronous code you already know, but the runtime behavior is asynchronous.
What This Section Covers
-
Coroutine Foundations — How normal function calls work, and what a coroutine’s suspend/resume model changes.
-
C++20 Syntax — The
co_await,co_yield, andco_returnkeywords, and how the compiler builds awaitables. -
Coroutine Machinery — Promise types and coroutine handles, the machinery behind suspension and resumption.
-
Advanced Topics — Symmetric transfer, custom allocation, HALO, and exception handling across suspension points.