A coroutine is a function that can actively suspend in the middle of execution and resume later. Unlike a thread, suspending a coroutine does not involve the OS kernel and is completed entirely in user space—the compiler splits the function body into multiple state machines, saves the context into a “coroutine frame” when suspended, and jumps back to continue execution when resumed.
C++20 introduced language-level support for coroutines. It does not provide out-of-the-box coroutines like Go or Lua; instead, it provides three keywords (co_await, co_yield, co_return) and a customizable infrastructure, allowing library authors to build their own coroutine models on top.
Why Coroutines?
Threads have two fundamental problems:
- High creation and switching overhead—each thread switch goes through kernel mode, saving/restoring the entire register set, taking hundreds of nanoseconds to a few microseconds
- High memory usage—each thread has independent stack space, 1~8MB by default. 10,000 threads ≈ 10GB memory
Coroutines solve these two problems in a very direct way:
| |
For a game server, a player connection is a continuous “request-response” session. If each connection occupies one thread, a few hundred players will crash the thread pool. With coroutines, ten thousand coroutines occupy only tens of MB, and the CPU switches only between coroutines that actually have work to do.
The Three Keywords
C++20 coroutines are built on three keywords. Once the compiler sees one of them in a function body, the function is no longer an ordinary function but a coroutine:
| Keyword | Role |
|---|---|
co_await | Suspend the coroutine and resume after some operation completes |
co_yield | Suspend the coroutine and produce a value; execution can continue later |
co_return | End the coroutine and return the final value |
| |
Low-Level Components of a Coroutine
C++20’s coroutine framework divides responsibilities among several roles; understanding them is the key to understanding coroutines.
Coroutine Frame
After the compiler splits a coroutine into a state machine, it needs a block of memory to store all local variables that live across suspension points. This memory is the coroutine frame, allocated on the heap (the compiler may optimize it to stack allocation).
| |
Key point: only variables that are still alive across a suspension point are placed in the frame. If a variable is destroyed before the suspension point, it remains on the ordinary stack. The compiler’s liveness analysis determines which variables go into the frame.
promise_type
Each coroutine is associated with a promise_type (unrelated to std::promise; the name is just a coincidence). It is the middleman between the compiler and the coroutine—controlling the coroutine’s lifetime, obtaining the return value, and handling exceptions:
| |
Flow when a coroutine is called:
| |
Awaitable Protocol
The co_await expr expression’s right-hand expr must be an awaitable, i.e. an object that satisfies the following three methods:
| |
Execution flow:
| |
Take a simple “wait one second” to demonstrate:
| |
This achieves a coroutine sleeping at a suspension point without occupying a thread—after the coroutine handle is registered with the timer, the current thread immediately returns to process other coroutines; 500ms later the timer triggers resume(), and the coroutine continues from the breakpoint.
coroutine_handle
std::coroutine_handle<> is a raw pointer wrapper around the coroutine frame. Through it you can:
| |
A Complete Generator Example
Generator is the simplest application of coroutines—a lazy sequence that can co_yield values multiple times and be pulled one by one from the outside:
| |
How the Generator Runs Step by Step
Think of a coroutine as a video tape that can be paused and resumed at any time—each pull from the outside plays a segment inside, and it freezes when it hits a pause point.
Although the fibonacci() function contains while (true), it does not compute all numbers in one go. Each gen.next() only lets it run one loop of the while, and it stops at co_yield:
| |
Like a tape measure—you pull once, a segment comes out (one number); if you don’t pull, it doesn’t move. Pulling 10 times = computing 10 numbers. while (true) does not freeze the CPU, because each co_yield actively returns execution to the outer main().
Back to the code mechanics: co_yield a → yield_value(a) stores a into promise_type.current, then suspends the coroutine; gen.next() → handle_.resume() resumes the coroutine from the line after co_yield, runs one loop of the while, hits co_yield again, and suspends again. There is no thread switching in the whole process.
Coroutines vs Threads vs Callbacks
| Threads | Coroutines | Callbacks | |
|---|---|---|---|
| Code structure | Sequential | Sequential (like synchronous code) | Nested/chained, prone to callback hell |
| Suspension mechanism | OS preemption | Active co_await | Function return + register callback |
| Switching cost | ~µs kernel mode | ~ns user mode | None (function call overhead) |
| Stack | ~1MB independent | ~KB coroutine frame | Determined by closure captures |
| Cost of 10,000 | ~10GB + scheduling storm | ~tens of MB | Depends on closure size |
Cooperative Scheduling: Your Responsibility
Threads use preemptive scheduling—as soon as the CPU timer interrupt arrives, the OS forcibly switches away no matter where you are. You don’t need to write anything; the OS guarantees fairness.
Coroutines use cooperative scheduling—they voluntarily yield execution only at co_await / co_yield / co_return. If a coroutine has no such suspension points, it will run to completion in one go like an ordinary function, starving all other coroutines on the entire thread:
| |
This is exactly the deeper meaning of the SleepAwaiter example at the beginning of the article: when a coroutine reaches co_await, it hands the handle to the timer, and the current thread immediately returns to process other coroutines—the OS does not switch for you; the coroutine voluntarily yields.
The while (true) { co_yield a; ... } in the Generator example is the same—the infinite loop does not block, because co_yield itself is a suspension point. Each time the outer gen.next() is called, the coroutine runs one loop of the while and then suspends, waiting for the next resume().
In other words: coroutines take scheduling responsibility away from the OS kernel. The saved overhead comes at a cost—you must take care of “when to yield execution” yourself.
The core value of coroutines is: they are written like synchronous code and run like asynchronous code. You don’t need to tear a continuous piece of business logic into callback fragments, and you don’t need a thread to sit idle waiting for IO.
Applications in Game Servers
The most typical application of coroutines in game servers is to turn stateful asynchronous flows into sequentially readable code:
1. Login Flow
| |
Without coroutines, these 6 steps would become 6 levels of nested callbacks, and error handling and the if(!player) logic would be scattered everywhere. Coroutines write the entire timing chain in a straight line, so you can see the whole picture at a glance.
2. Conditional Waiting
| |
500 dungeon instances each waiting for their own players: with threads = 500 sleeping threads. With coroutines = 500 coroutine frames + 1 thread-driven timer.
3. Quantitative Comparison: Why Not Just Spawn More Threads?
The most important conclusion here is not “coroutines are faster than threads”, but “coroutines are cheaper than threads”.
Cheap enough that you can create one coroutine per player, while you cannot afford to do that with threads.
Scenario: 1000 players log in at the same time, each with 4 asynchronous IO steps (receive packet → query DB → load scene → send response), totaling about 85~130ms per player.
Coroutine version (1 thread + event loop). Core: after co_await registers the handle with the event loop, it returns immediately, and the thread does not block:
| |
Thread pool version (what you can do in reality). Each sleep occupies the thread, and the number of threads is the bottleneck:
| |
Actual results—coroutines with 1 thread, thread pool with different sizes:
| Coroutines | Thread Pool 8 | Thread Pool 16 | Thread Pool 32 | |
|---|---|---|---|---|
| Concurrency unit | 1000 coroutines | 8 threads | 16 threads | 32 threads |
| Total time | ~180 ms | ~13 s | ~6.5 s | ~3.3 s |
| Memory | ~0.4 MB | ~8 MB | ~16 MB | ~32 MB |
The trend is clear: the larger the thread pool, the faster it is, but to catch up with the coroutine’s 180ms, you need ~1000 threads.
Key logic:
If you can use a thread pool of 1000, and your machine has enough memory, and it is not a real IO load—
then the thread pool performs the same as coroutines.
Because as long as the number of concurrent tasks <= the number of threads, everyone can “block on their own and wait on their own”.
But: threads are a scarce resource. The operating system has limits on the number of threads, each thread must be allocated an independent kernel stack, and context switching consumes CPU time. On a real game server, it is almost impossible to use one thread to serve one player connection.
The essential advantage of coroutines is not speed, but “cheapness”. So cheap that you can create a coroutine for every concurrent task, while you cannot do that with threads. As a result, what you get with coroutines is “concurrency at the task-count level”, while with a thread pool you can only get “concurrency at the thread-pool-size level”.
So the comparison is not “coroutines vs thread pool 20”, but:
| |
Not enough threads → queuing → latency explodes. Coroutines are cheap enough → no queuing → latency depends only on the task itself.
The Cost of Coroutines
Coroutines are not a silver bullet:
- Heap allocation: creating a coroutine usually requires
operator newto allocate the coroutine frame (the scenarios where the compiler can optimize it away are limited) - Template bloat: combinations of
promise_typeand awaitable types lead to a large number of template instantiations - Debugging difficulty: the stack frame is split into a state machine; stack traces show a bunch of
__coro_resumeintermediate frames, and the logical call chain is lost - Immature ecosystem: C++20 only provides low-level infrastructure, with no standardized
Task<T>or scheduler. Production environments generally use cppcoro or their own wrappers - Copied parameter trap: coroutine parameters are copied to the frame by default; passing references easily leads to dangling references (the frame may outlive the referenced source)
| |
Q&A
Please explain the low-level mechanism of C++20 coroutines. What roles do co_await, promise_type, coroutine_handle, and the coroutine frame each play?
Coroutine frame—after the compiler splits the coroutine body into a state machine, all local variables and parameters that live across suspension points are stored on this heap memory. It uses switch(state) to implement “continue from the last breakpoint”.
promise_type—the middleman between the compiler and the coroutine. It controls when the coroutine starts (initial_suspend), when it is destroyed (final_suspend), how the co_return value is passed out, how uncaught exceptions are handled, and how the co_yield value is temporarily stored.
coroutine_handle—a raw pointer wrapper around the coroutine frame. Through it you can resume() (resume execution), done() (check whether it has finished), and destroy() (manually release the frame). await_suspend receives this handle; register it with an event source such as IO/timer, and call resume() when the event occurs.
co_await—the suspension point of a coroutine. The execution flow of co_await expr: first call await_ready(); if true, skip directly without suspending; if false, save the state, call await_suspend(handle) to hand the handle to the outside, and the coroutine yields execution; later the outside calls handle.resume() → the return value of await_resume() becomes the result of co_await, and the coroutine continues from the next line.
What is the difference between coroutines and threads? Threads are preempted by the OS, switching into kernel mode (~µs), with an independent stack of ~1MB; coroutines suspend actively, switch purely in user mode (~ns), with a coroutine frame of ~KB. 10,000 threads ≈ 10GB + scheduling storm; 10,000 coroutines ≈ tens of MB + zero kernel overhead. The core problem coroutines solve is “make asynchronous code look like synchronous code, while not wasting threads waiting for IO”.