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