Detailed Explanation of C++ Coroutines

Words: 3069

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:

  1. 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
  2. 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:

1
2
3
4
5
线程:  [task A 执行] → [OS 抢占] → [task B 执行] → [OS 抢占] → ...
       ↑ 被动切换,每次进出内核态                  ↑ 独立栈 ~MB

协程:  [task A 执行] → [co_await 挂起] → [task B 执行] → [co_await 挂起] → ...
       ↑ 主动挂起,纯用户态                        ↑ 协程帧 ~KB

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:

KeywordRole
co_awaitSuspend the coroutine and resume after some operation completes
co_yieldSuspend the coroutine and produce a value; execution can continue later
co_returnEnd the coroutine and return the final value
cpp
1
2
3
4
5
6
7
8
9
// 普通函数
int normal_fn() { return 42; }

// 协程 —— 只要用了 co_* 关键字就是协程
Task<int> coro_fn() {
    int x = co_await some_async_op();  // 挂起点 1
    int y = x * 2;
    co_return y;                        // 挂起点 2(结束)
}

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).

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Task<int> compute(std::string name) {
    int a = 100;                   // 在帧上
    int b = co_await fetch(a);     // 挂起!a 和 name 必须保存在帧上
    int c = a + b;                 // a 从上个挂起点恢复
    co_return c + name.size();
}

// 编译后大致等价于:
struct __compute_frame {
    std::string name;       // 参数
    int a, b, c;            // 跨挂起点的局部变量
    promise_type __promise;
    int __state = 0;        // 状态编号:0=起点, 1=co_await后, 2=完成
};
// resume() 时用 switch(__state) 跳到对应位置继续执行

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:

cpp
1
2
3
4
5
6
7
struct Task<T>::promise_type {
    Task<T> get_return_object();    // 协程被调用时,返回给调用者的对象
    suspend_always initial_suspend(); // 协程一开始是否立即挂起
    suspend_always final_suspend();   // 协程结束时是否挂起(不挂起则自动析构帧)
    void return_value(T value);       // co_return value → 走这里
    void unhandled_exception();       // 协程内抛了未捕获异常 → 走这里
};

Flow when a coroutine is called:

1
2
3
4
5
6
7
8
1. operator new 分配协程帧
2. 把参数拷贝/移动到帧上
3. 在帧上构造 promise_type
4. promise.get_return_object() → 返回给调用者
5. co_await promise.initial_suspend() → 决定是否一开始就挂起
6. 执行协程体直到 co_return 或 co_await 或异常
7. co_await promise.final_suspend() → 决定协程帧是否立即释放
8. 析构 promise + 局部变量 + operator delete 帧

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:

cpp
1
2
3
4
5
struct Awaitable {
    bool await_ready();                      // 能立刻完成?return true → 不挂起
    void await_suspend(coroutine_handle<>);  // 挂起时调用,获得协程句柄
    T    await_resume();                     // 恢复时调用,返回 co_await 的结果值
};

Execution flow:

1
2
3
4
5
6
7
8
9
co_await expr:
  1. expr.await_ready()?
       true  → 直接走 4,不挂起(高效路径)
       false → 进入 2
  2. 挂起协程(保存状态到帧,切换出去)
  3. expr.await_suspend(handle)
       - 把 handle 保存到某个地方(比如 IO 完成队列)
       - 稍后外部事件触发 handle.resume()
  4. expr.await_resume() 的返回值 = co_await 的结果

Take a simple “wait one second” to demonstrate:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
struct SleepAwaiter {
    chrono::milliseconds delay_;

    bool await_ready() { return false; }  // 永远挂起

    void await_suspend(coroutine_handle<> h) {
        // 把协程句柄注册到定时器,delay_ 毫秒后 h.resume()
        timer_system::schedule(delay_, [h] { h.resume(); });
    }

    void await_resume() {}  // 无返回值
};

Task<> wait_and_print() {
    cout << "start" << endl;
    co_await SleepAwaiter{500ms};  // 挂起 500ms
    cout << "500ms later" << endl;
}

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:

cpp
1
2
3
4
5
handle.resume();        // 恢复协程执行
handle.done();          // 协程是否已结束
handle.destroy();       // 手动销毁协程帧
handle.address();       // 获取帧地址(可用于调试或哈希)
handle.promise();       // 访问帧内的 promise_type

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:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <coroutine>
#include <iostream>
#include <optional>
using namespace std;

template<typename T>
struct Generator {
    struct promise_type {
        optional<T> current;

        Generator get_return_object() {
            return Generator{coroutine_handle<promise_type>::from_promise(*this)};
        }
        suspend_always initial_suspend() { return {}; }  // 一开始挂起
        suspend_always final_suspend() noexcept { return {}; }
        suspend_always yield_value(T value) {
            current = value;    // 保存产出值
            return {};          // 挂起
        }
        void return_void() {}
        void unhandled_exception() { terminate(); }
    };

    coroutine_handle<promise_type> handle_;

    explicit Generator(coroutine_handle<promise_type> h) : handle_(h) {}
    ~Generator() { if (handle_) handle_.destroy(); }

    // 不可拷贝
    Generator(const Generator&) = delete;
    Generator& operator=(const Generator&) = delete;
    Generator(Generator&& other) noexcept : handle_(exchange(other.handle_, nullptr)) {}

    // 迭代器:每次 ++ 就 resume 协程取下一个 co_yield 值
    optional<T> next() {
        if (!handle_ || handle_.done()) return nullopt;
        handle_.resume();
        if (handle_.done()) return nullopt;
        return handle_.promise().current;
    }
};

// 使用 Generator 生成斐波那契数列
Generator<int> fibonacci() {
    int a = 0, b = 1;
    while (true) {
        co_yield a;
        auto next = a + b;
        a = b;
        b = next;
    }
}

int main() {
    auto gen = fibonacci();
    for (int i = 0; i < 10; ++i) {
        cout << *gen.next() << " ";  // 0 1 1 2 3 5 8 13 21 34
    }
}

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
第 1 次 gen.next():
  a=0, b=1 → co_yield a → 输出 0 → 暂停!(next 还没算呢)
  停在哪里:co_yield 的下一行

第 2 次 gen.next():
  从上次停的地方继续 → next = 0+1 = 1 → a=1, b=1 → 转回 while 头
  → co_yield a → 输出 1 → 暂停!

第 3 次 gen.next():
  继续 → next = 1+1 = 2 → a=1, b=2 → co_yield a → 输出 1 → 暂停!

第 4 次 gen.next():
  继续 → next = 1+2 = 3 → a=2, b=3 → co_yield a → 输出 2 → 暂停!

第 5 次 gen.next():
  继续 → next = 2+3 = 5 → a=3, b=5 → co_yield a → 输出 3 → 暂停!

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

ThreadsCoroutinesCallbacks
Code structureSequentialSequential (like synchronous code)Nested/chained, prone to callback hell
Suspension mechanismOS preemptionActive co_awaitFunction return + register callback
Switching cost~µs kernel mode~ns user modeNone (function call overhead)
Stack~1MB independent~KB coroutine frameDetermined by closure captures
Cost of 10,000~10GB + scheduling storm~tens of MBDepends 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:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// 危险:死循环里没有挂起点,整个线程卡死
Task<> bad_loop() {
    while (true) {
        heavy_compute();  // 纯计算,永远不交出执行权
    }
}

// 安全:每次循环都主动挂起,让出 CPU 给其他协程
Task<> good_loop() {
    while (true) {
        heavy_compute();
        co_await yield();  // 显式让出,调度器去跑别人
    }
}

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

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Task<> handle_login(connection_id cid) {
    auto packet = co_await recv_async(cid);          // 1. 等客户端发握手包
    auto player = co_await db_query(packet.uid);      // 2. 查数据库(异步)
    if (!player) {
        co_await send_async(cid, "login failed");
        co_return;
    }
    auto scene = world.get_scene(player->last_pos);   // 3. 获取场景
    co_await scene->enter_async(player);               // 4. 进入场景(可能异步加载)
    co_await send_async(cid, "login ok");
    player->online = true;
}

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

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// 等一个条件成熟,同时设超时
Task<bool> wait_for_players(int32 instance_id, int count, chrono::seconds timeout) {
    auto deadline = chrono::steady_clock::now() + timeout;
    while (world.get_instance(instance_id).player_count() < count) {
        if (chrono::steady_clock::now() > deadline) {
            co_return false;  // 超时
        }
        co_await SleepAwaiter{10ms};  // 挂起 10ms,让出执行权
    }
    co_return true;
}

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:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
struct AsyncOp {
    int delay_ms_;
    EventLoop& loop_;

    bool await_ready() noexcept { return false; }
    void await_suspend(coroutine_handle<> h) noexcept {
        loop_.schedule(h, delay_ms_);  // 注册唤醒时间,线程立即返回
    }
    void await_resume() noexcept {}
};

Task player_login(int id, EventLoop& loop) {
    co_await AsyncOp{20 + id % 30, loop}; // 收包
    co_await AsyncOp{30 + id % 50, loop}; // 查 DB
    co_await AsyncOp{25 + id % 30, loop}; // 加载场景
    co_await AsyncOp{10 + id % 15, loop}; // 发响应
}

Thread pool version (what you can do in reality). Each sleep occupies the thread, and the number of threads is the bottleneck:

cpp
1
2
3
4
5
6
void player_login(int id) {
    sleep_for(milliseconds(20 + id % 30)); // 线程被占着,什么都干不了
    sleep_for(milliseconds(30 + id % 50));
    sleep_for(milliseconds(25 + id % 30));
    sleep_for(milliseconds(10 + id % 15));
}

Actual results—coroutines with 1 thread, thread pool with different sizes:

CoroutinesThread Pool 8Thread Pool 16Thread Pool 32
Concurrency unit1000 coroutines8 threads16 threads32 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:

1
2
协程:    1000 任务 × 1000 协程 → 并发度 1000 → 耗时 ≈ 最长链
线程池:  1000 任务 × N 线程     → 并发度 N    → 耗时 ≈ 最长链 × ceil(1000/N)

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 new to allocate the coroutine frame (the scenarios where the compiler can optimize it away are limited)
  • Template bloat: combinations of promise_type and 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_resume intermediate 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)
cpp
1
2
3
4
5
6
// 危险!
Task<> foo(const std::string& name) {
    co_await something();  // name 引用存到了帧上
    cout << name;          // 此时 name 引用的原始对象可能已经析构
}
// 安全:传值或 shared_ptr 到帧上

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”.

This post contains some AI-assisted content, reviewed and edited by the author before publishing.
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...