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 caller waits. The stack frame lives and dies in lockstep with that single invocation. This model has served us well for decades. 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.
C++20 coroutines change the rules. 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. No blocked threads. No callback chains. No lost context.
This is not a minor syntactic convenience. It is a fundamental shift in how you can structure programs that wait.
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.