协程句柄 coroutine_handle
什么是 coroutine_handle
std::coroutine_handle 是 C++20 提供的一个轻量级句柄类型,用来从协程外部控制协程的执行。它是一个非拥有的(non-owning)指针,指向协程帧,提供恢复(resume)、销毁(destroy)和状态查询(done)等操作。
coroutine_handle 是协程机制中"外部控制"的唯一手段——调用者通过它来恢复挂起的协程或销毁协程帧。它不管理协程帧的生命周期,生命周期管理是返回对象(如 Task、Generator)的职责。
coroutine_handle 的两种形式
| 形式 | 说明 |
|---|---|
std::coroutine_handle<void>(或 std::coroutine_handle<>) | 类型擦除版本,不知道关联的 promise 类型 |
std::coroutine_handle<PromiseType> | 带类型的版本,可以访问承诺对象 |
coroutine_handle<PromiseType> 可以隐式转换为 coroutine_handle<>,反过来不行。
成员函数一览
| 方法 | 说明 |
|---|---|
resume() / operator()() | 恢复挂起的协程 |
destroy() | 销毁协程帧(释放内存) |
done() | 检查协程是否在最终挂起点(已结束) |
operator bool() | 检查句柄是否有效(非空) |
promise() | 获取承诺对象的引用(仅带类型版本) |
address() | 获取底层指针(可用于序列化) |
from_promise(p) | 从承诺对象创建句柄(静态方法) |
from_address(addr) | 从原始指针恢复句柄(静态方法) |
基本示例
#include <coroutine>
#include <iostream>
#include <string>
#include <vector>
#include <functional>
// ============================
// 示例1:coroutine_handle 的基本操作
// ============================
struct Task {
struct promise_type {
Task get_return_object() {
// from_promise:从承诺对象创建句柄
return Task{
std::coroutine_handle<promise_type>::from_promise(*this)
};
}
std::suspend_always initial_suspend() noexcept { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle<promise_type> handle_;
explicit Task(std::coroutine_handle<promise_type> h) : handle_(h) {}
~Task() {
if (handle_) {
handle_.destroy(); // 销毁协程帧
}
}
Task(const Task&) = delete;
Task& operator=(const Task&) = delete;
Task(Task&& o) noexcept : handle_(o.handle_) { o.handle_ = nullptr; }
};
Task demo_coroutine() {
std::cout << "步骤 1" << std::endl;
co_await std::suspend_always{};
std::cout << "步骤 2" << std::endl;
co_await std::suspend_always{};
std::cout << "步骤 3" << std::endl;
}
void basic_handle_demo() {
auto task = demo_coroutine();
auto& h = task.handle_;
// operator bool:检查句柄是否有效
std::cout << "句柄有效: " << std::boolalpha << static_cast<bool>(h) << std::endl;
// done():检查是否已完成(在最终挂起点)
std::cout << "已完成: " << h.done() << std::endl;
// resume():恢复执行
h.resume(); // 步骤 1
std::cout << "已完成: " << h.done() << std::endl;
// operator()() 等价于 resume()
h(); // 步骤 2
std::cout << "已完成: " << h.done() << std::endl;
h.resume(); // 步骤 3,之后到达 final_suspend
std::cout << "已完成: " << h.done() << std::endl; // true
}
// ============================
// 示例2:通过 promise() 访问承诺对象
// ============================
struct ValueTask {
struct promise_type {
int result = 0;
ValueTask get_return_object() {
return ValueTask{
std::coroutine_handle<promise_type>::from_promise(*this)
};
}
std::suspend_always initial_suspend() noexcept { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_value(int v) { result = v; }
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle<promise_type> handle_;
explicit ValueTask(std::coroutine_handle<promise_type> h) : handle_(h) {}
~ValueTask() { if (handle_) handle_.destroy(); }
ValueTask(const ValueTask&) = delete;
ValueTask& operator=(const ValueTask&) = delete;
ValueTask(ValueTask&& o) noexcept : handle_(o.handle_) { o.handle_ = nullptr; }
int get_result() const {
// promise():获取承诺对象的引用,读取结果
return handle_.promise().result;
}
};
ValueTask compute() {
co_return 42;
}
void promise_access_demo() {
auto task = compute();
task.handle_.resume();
std::cout << "结果: " << task.get_result() << std::endl; // 42
}
// ============================
// 示例3:address / from_address 地址转换
// ============================
// 地址转换让你可以在类型擦除的容器中存储协程句柄
void address_demo() {
auto task = demo_coroutine();
// 导出为原始指针
void* addr = task.handle_.address();
std::cout << "协程地址: " << addr << std::endl;
// 从原始指针恢复(类型擦除版本)
auto generic_handle = std::coroutine_handle<>::from_address(addr);
generic_handle.resume(); // 步骤 1
// 也可以恢复为带类型的版本
auto typed_handle = std::coroutine_handle<Task::promise_type>::from_address(addr);
typed_handle.resume(); // 步骤 2
}
// ============================
// 示例4:类型擦除的协程调度器
// ============================
class SimpleScheduler {
// 用 void* 存储协程句柄,实现类型擦除
std::vector<std::coroutine_handle<>> ready_queue_;
public:
// 添加一个待执行的协程
void schedule(std::coroutine_handle<> h) {
ready_queue_.push_back(h);
}
// 运行所有就绪的协程(各执行一步)
void run_once() {
auto current = std::move(ready_queue_);
ready_queue_.clear();
for (auto h : current) {
if (h && !h.done()) {
h.resume();
// 如果协程还没结束,放回队列
if (!h.done()) {
ready_queue_.push_back(h);
}
}
}
}
// 运行直到所有协程完成
void run_all() {
while (!ready_queue_.empty()) {
run_once();
}
}
bool empty() const { return ready_queue_.empty(); }
};
// 调度感知的协程类型
struct ScheduledTask {
struct promise_type {
SimpleScheduler* scheduler = nullptr;
ScheduledTask get_return_object() {
return ScheduledTask{
std::coroutine_handle<promise_type>::from_promise(*this)
};
}
std::suspend_always initial_suspend() noexcept { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_void() {}
void unhandled_exception() { std::terminate(); }
};
std::coroutine_handle<promise_type> handle_;
explicit ScheduledTask(std::coroutine_handle<promise_type> h) : handle_(h) {}
~ScheduledTask() { if (handle_) handle_.destroy(); }
ScheduledTask(const ScheduledTask&) = delete;
ScheduledTask& operator=(const ScheduledTask&) = delete;
ScheduledTask(ScheduledTask&& o) noexcept : handle_(o.handle_) { o.handle_ = nullptr; }
};
ScheduledTask task_a() {
std::cout << "A-1" << std::endl;
co_await std::suspend_always{};
std::cout << "A-2" << std::endl;
co_await std::suspend_always{};
std::cout << "A-3" << std::endl;
}
ScheduledTask task_b() {
std::cout << "B-1" << std::endl;
co_await std::suspend_always{};
std::cout << "B-2" << std::endl;
}
void scheduler_demo() {
SimpleScheduler scheduler;
auto a = task_a();
auto b = task_b();
// 将两个协程加入调度器(使用类型擦除的 coroutine_handle<>)
scheduler.schedule(a.handle_);
scheduler.schedule(b.handle_);
// 交替执行
std::cout << "--- 开始调度 ---" << std::endl;
scheduler.run_all();
// 输出交替:A-1, B-1, A-2, B-2, A-3
}
// ============================
// 示例5:noop_coroutine(空操作协程)
// ============================
void noop_demo() {
// std::noop_coroutine() 返回一个特殊句柄
// resume 和 destroy 对它都是空操作
auto noop = std::noop_coroutine();
// 可以安全地调用 resume 和 done
std::cout << "noop done: " << std::boolalpha << noop.done() << std::endl; // false
noop.resume(); // 空操作,什么都不做
std::cout << "noop 地址: " << noop.address() << std::endl;
// noop_coroutine 常用于对称转移中作为"返回调用者"的默认值
}
int main() {
std::cout << "=== 基本操作 ===" << std::endl;
basic_handle_demo();
std::cout << "\n=== promise 访问 ===" << std::endl;
promise_access_demo();
std::cout << "\n=== 地址转换 ===" << std::endl;
address_demo();
std::cout << "\n=== 调度器 ===" << std::endl;
scheduler_demo();
std::cout << "\n=== noop_coroutine ===" << std::endl;
noop_demo();
return 0;
}对称转移(Symmetric Transfer)
对称转移是 coroutine_handle 的一个关键应用。当 await_suspend 返回一个 coroutine_handle 时,当前协程挂起后直接恢复返回的那个协程,而不是返回到调用者。这避免了深层协程链导致的栈溢出。
// 对称转移示例
struct SymmetricAwaiter {
std::coroutine_handle<> target;
bool await_ready() const noexcept { return false; }
// 返回 coroutine_handle → 对称转移
// 挂起当前协程,直接恢复 target 协程
std::coroutine_handle<> await_suspend(std::coroutine_handle<>) const noexcept {
if (target) return target;
return std::noop_coroutine(); // 没有目标时返回 noop,相当于返回调用者
}
void await_resume() const noexcept {}
};对称转移 vs 普通恢复:
| 方式 | 栈消耗 | 适用场景 |
|---|---|---|
h.resume()(调用者恢复) | 每层嵌套消耗栈帧 | 简单场景 |
await_suspend 返回 handle(对称转移) | 不消耗额外栈帧 | 深层协程链 |
适用场景
- 协程调度器:用类型擦除的
coroutine_handle<>管理多个协程 - 协程链式等待:通过对称转移连接多个协程
- 协程池:用
address()/from_address()在容器中存储协程 - 自定义 Awaiter:在
await_suspend中操作句柄控制流
常见问题
coroutine_handle 是拥有语义还是引用语义?
引用语义(非拥有)。coroutine_handle 就像一个原始指针——它不负责协程帧的生命周期管理。通常由返回对象(Task、Generator 等)在析构时调用 handle.destroy()。
什么时候调用 destroy?
当 final_suspend 返回 suspend_always 时,协程帧不会自动销毁,需要你在返回对象的析构函数中调用 handle.destroy()。如果 final_suspend 返回 suspend_never,协程帧自动销毁,不能再调用 destroy()。
对已完成的协程调用 resume 会怎样?
未定义行为。必须在调用 resume() 之前检查 done() 是否为 false。
对已销毁的协程调用 resume 或 destroy 会怎样?
未定义行为。一旦 destroy() 被调用,句柄就不能再使用了。
coroutine_handle 可以在线程间传递吗?
可以,但恢复协程时所在的线程可能和挂起时不同。标准说如果两个执行代理都是 std::thread 或 std::jthread,跨线程恢复是合法的。
注意事项
coroutine_handle是非拥有的,不要依赖它来管理协程帧的生命周期resume()只能在挂起的、未完成的协程上调用destroy()只能在挂起的协程上调用,且只能调用一次done()只能在挂起的协程上调用from_address恢复的句柄类型必须和原始句柄的 promise 类型匹配noop_coroutine()返回的句柄可以安全地 resume 和 destroy(都是空操作)- 对称转移时用
noop_coroutine()作为"不恢复任何协程"的默认值
编译器支持情况
| 编译器 | 最低支持版本 |
|---|---|
| GCC | 10.0 |
| Clang | 14.0 |
| MSVC | 19.28 (VS 2019 16.8) |
总结
std::coroutine_handle 是从外部控制协程的唯一途径。它提供了 resume() 恢复执行、destroy() 销毁协程帧、done() 查询完成状态、promise() 访问承诺对象等核心操作。句柄有类型擦除版本(coroutine_handle<>)和带 promise 类型的版本,前者适合用在调度器等需要统一管理不同类型协程的场景。address() 和 from_address() 支持将句柄转换为原始指针以便存储。对称转移(await_suspend 返回 coroutine_handle)是实现高效协程链的关键技术,它让协程之间的控制权转移不消耗额外栈空间。noop_coroutine() 提供了一个安全的"空操作"句柄,常用于对称转移中作为默认值。