协程 (C++20)
协程是一种可以暂停执行并在以后恢复的函数。协程是无栈的:它们通过返回给调用者来暂停执行,并且恢复执行所需的数据与栈分开存储。这允许顺序代码以异步方式执行(例如,在没有显式回调的情况下处理非阻塞I/O),并且还支持对惰性计算的无限序列和其他用例的算法。
如果函数的定义包含以下任何一项,则该函数是协程:
- co_await 表达式 — 用于暂停执行直到恢复
task<> tcp_echo_server() { char data[1024]; while (true) { std::size_t n = co_await socket.async_read_some(buffer(data)); co_await async_write(socket, buffer(data, n)); } }
- co_yield 表达式 — 用于暂停执行并返回一个值
generator<unsigned int> iota(unsigned int n = 0) { while (true) co_yield n++; }
- co_return 语句 — 用于完成执行并返回一个值
lazy<int> f() { co_return 7; }
每个协程都必须有一个满足以下要求的返回类型。
目录 |
[编辑] 限制
协程不能使用可变参数、普通的return语句或占位符返回类型(auto
或Concept)。
Consteval 函数、constexpr 函数、构造函数、析构函数和main 函数不能是协程。
[编辑] 执行
每个协程都与以下对象关联:
- promise 对象,在协程内部操作。协程通过此对象提交其结果或异常。Promise 对象与std::promise没有任何关联。
- 协程句柄,在协程外部操作。这是一个非拥有句柄,用于恢复协程的执行或销毁协程帧。
- 协程状态,这是一个内部的、动态分配的存储(除非分配被优化掉),包含:
- promise 对象
- 参数(全部按值复制)
- 当前暂停点的一些表示,以便恢复时知道从何处继续,销毁时知道哪些局部变量在作用域内
- 生命周期跨越当前暂停点的局部变量和临时变量。
当协程开始执行时,它会执行以下操作:
- 使用operator new分配协程状态对象。
- 将所有函数参数复制到协程状态:按值参数被移动或复制,按引用参数仍然是引用(因此,如果在引用对象的生命周期结束后协程恢复,可能会变为悬空引用——请参阅下面的示例)。
- 调用 promise 对象的构造函数。如果 promise 类型有一个接受所有协程参数的构造函数,则使用复制后的协程参数调用该构造函数。否则调用默认构造函数。
- 调用promise.get_return_object()并将结果保存在局部变量中。当协程首次暂停时,该调用的结果将返回给调用者。在此步骤之前(含此步骤)抛出的任何异常都会传播回调用者,而不是放入 promise 中。
- 调用promise.initial_suspend()并
co_await
其结果。典型的Promise
类型要么返回std::suspend_always(用于惰性启动的协程),要么返回std::suspend_never(用于急切启动的协程)。 - 当co_await promise.initial_suspend()恢复时,开始执行协程的主体。
参数变为悬空的一些示例
#include <coroutine> #include <iostream> struct promise; struct coroutine : std::coroutine_handle<promise> { using promise_type = ::promise; }; struct promise { coroutine get_return_object() { return {coroutine::from_promise(*this)}; } std::suspend_always initial_suspend() noexcept { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void return_void() {} void unhandled_exception() {} }; struct S { int i; coroutine f() { std::cout << i; co_return; } }; void bad1() { coroutine h = S{0}.f(); // S{0} destroyed h.resume(); // resumed coroutine executes std::cout << i, uses S::i after free h.destroy(); } coroutine bad2() { S s{0}; return s.f(); // returned coroutine can't be resumed without committing use after free } void bad3() { coroutine h = [i = 0]() -> coroutine // a lambda that's also a coroutine { std::cout << i; co_return; }(); // immediately invoked // lambda destroyed h.resume(); // uses (anonymous lambda type)::i after free h.destroy(); } void good() { coroutine h = [](int i) -> coroutine // make i a coroutine parameter { std::cout << i; co_return; }(0); // lambda destroyed h.resume(); // no problem, i has been copied to the coroutine // frame as a by-value parameter h.destroy(); }
当协程到达暂停点时
- 之前获得的返回对象会返回给调用者/恢复者,如果需要,还会隐式转换为协程的返回类型。
当协程到达co_return语句时,它执行以下操作:
- 对于以下情况,调用promise.return_void():
- co_return;
- co_return expr;其中expr的类型是void
- 或者对于co_return expr;,如果expr是非void类型,则调用promise.return_value(expr)
- 以相反的创建顺序销毁所有具有自动存储持续时间的变量。
- 调用promise.final_suspend()并co_await其结果。
协程执行到末尾等同于co_return;,除非在Promise
的作用域中找不到return_void
的声明,这种情况下行为是未定义的。如果函数的函数体中没有定义协程关键字,则无论其返回类型如何,它都不是协程,并且如果返回类型不是(可能带有cv限定符的)void,则执行到末尾会导致未定义行为。
// assuming that task is some coroutine task type task<void> f() { // not a coroutine, undefined behavior } task<void> g() { co_return; // OK } task<void> h() { co_await g(); // OK, implicit co_return; }
如果协程因未捕获的异常而终止,它将执行以下操作:
- 捕获异常并在catch块内调用promise.unhandled_exception()
- 调用promise.final_suspend()并co_await其结果(例如,恢复后续操作或发布结果)。从这一点恢复协程是未定义行为。
当协程状态因co_return或未捕获的异常而终止,或者通过其句柄被销毁时,它将执行以下操作:
- 调用 promise 对象的析构函数。
- 调用函数参数副本的析构函数。
- 调用operator delete以释放协程状态使用的内存。
- 将执行权返回给调用者/恢复者。
[编辑] 动态分配
协程状态通过非数组operator new动态分配。
如果Promise
类型定义了类级别的替换,则将使用它,否则将使用全局operator new。
如果Promise
类型定义了带有额外参数的operator new的放置形式,并且它们与参数列表匹配(其中第一个参数是请求的大小,类型为std::size_t,其余参数是协程函数参数),这些参数将传递给operator new(这使得可以为协程使用前置分配器约定)。
如果满足以下条件,对operator new的调用可以被优化掉(即使使用了自定义分配器):
- 协程状态的生命周期严格嵌套在调用者的生命周期内,并且
- 协程帧的大小在调用点已知。
在这种情况下,协程状态嵌入在调用者的栈帧中(如果调用者是普通函数)或协程状态中(如果调用者是协程)。
如果分配失败,协程抛出std::bad_alloc,除非Promise
类型定义了成员函数Promise::get_return_object_on_allocation_failure()。如果定义了该成员函数,分配将使用operator new的nothrow形式,并且在分配失败时,协程立即将从Promise::get_return_object_on_allocation_failure()获得的对象返回给调用者,例如:
struct Coroutine::promise_type { /* ... */ // ensure the use of non-throwing operator-new static Coroutine get_return_object_on_allocation_failure() { std::cerr << __func__ << '\n'; throw std::bad_alloc(); // or, return Coroutine(nullptr); } // custom non-throwing overload of new void* operator new(std::size_t n) noexcept { if (void* mem = std::malloc(n)) return mem; return nullptr; // allocation failure } };
[编辑] Promise
Promise
类型由编译器根据协程的返回类型使用std::coroutine_traits确定。
正式地,令
-
R
和Args...
分别表示协程的返回类型和参数类型列表, -
ClassT
表示如果协程被定义为非静态成员函数,则其所属的类类型, - cv 表示如果协程被定义为非静态成员函数,则在函数声明中声明的cv限定符,
其Promise
类型由以下方式确定:
- std::coroutine_traits<R, Args...>::promise_type,如果协程未定义为隐式对象成员函数,
- std::coroutine_traits<R,
- std::coroutine_traits<R,
例如:
如果协程定义为... | 那么它的Promise 类型是... |
---|---|
task<void> foo(int x); | std::coroutine_traits<task<void>, int>::promise_type |
task<void> Bar::foo(int x) const; | std::coroutine_traits<task<void>, const Bar&, int>::promise_type |
task<void> Bar::foo(int x) &&; | std::coroutine_traits<task<void>, Bar&&, int>::promise_type |
[编辑] co_await
一元运算符co_await暂停协程并将控制权返回给调用者。
co_await expr |
|||||||||
co_await表达式只能出现在常规函数体(包括lambda表达式的函数体)中的潜在求值表达式中,并且不能出现在:
- 处理程序中,
- 声明语句中,除非它出现在该声明语句的初始化器中,
- init-statement的简单声明中(参见
if
、switch
、for
和[[../range-for|range-for]]),除非它出现在该init-statement的初始化器中, - 默认参数中,或
- 具有静态或线程存储持续时间的块作用域变量的初始化器中。
(C++26 起) |
首先,expr 转换为一个可等待对象,转换方式如下:
- 如果expr是由初始暂停点、最终暂停点或yield表达式生成的,则可等待对象是expr本身。
- 否则,如果当前协程的
Promise
类型有成员函数await_transform
,则可等待对象是promise.await_transform(expr)。 - 否则,可等待对象是expr本身。
然后,获取等待器对象,方式如下:
- 如果operator co_await的重载决议得到一个最佳重载,则等待器是该调用的结果
- awaitable.operator co_await() 对于成员重载,
- operator co_await(static_cast<Awaitable&&>(awaitable)) 对于非成员重载。
- 否则,如果重载决议找不到operator co_await,则等待器是awaitable本身。
- 否则,如果重载决议存在歧义,程序格式错误。
如果上述表达式是一个prvalue,则等待器对象是一个从其实体化的临时对象。否则,如果上述表达式是一个glvalue,则等待器对象是它引用的对象。
然后,调用awaiter.await_ready()(这是一个捷径,如果已知结果已就绪或可以同步完成,则避免暂停的开销)。如果其结果在上下文转换为bool后为false,则:
- 协程被暂停(其协程状态填充了局部变量和当前暂停点)。
- 调用awaiter.await_suspend(handle),其中handle是表示当前协程的协程句柄。在该函数内部,可以通过该句柄观察暂停的协程状态,并且该函数负责安排它在某个执行器上恢复执行,或者销毁它(返回false算作调度)。
- 如果
await_suspend
返回void,控制权立即返回给当前协程的调用者/恢复者(此协程保持暂停),否则 - 如果
await_suspend
返回bool,
- 值true将控制权返回给当前协程的调用者/恢复者
- 值false恢复当前协程。
- 如果
await_suspend
返回其他协程的协程句柄,则恢复该句柄(通过调用handle.resume())(请注意,这最终可能导致当前协程恢复)。 - 如果
await_suspend
抛出异常,则捕获异常,恢复协程,并立即重新抛出异常。
- 如果
最后,调用awaiter.await_resume()(无论协程是否暂停),其结果是整个co_await expr表达式的结果。
如果协程在co_await表达式中被暂停,并且稍后恢复,则恢复点紧邻在调用awaiter.await_resume()之前。
请注意,协程在进入awaiter.await_suspend()之前已完全暂停。它的句柄可以与另一个线程共享,并在await_suspend()函数返回之前恢复。(请注意,默认的内存安全规则仍然适用,因此,如果协程句柄在没有锁的情况下跨线程共享,则等待器应至少使用释放语义,而恢复器应至少使用获取语义。)例如,协程句柄可以放入回调中,当异步I/O操作完成时,安排在线程池上运行。在这种情况下,由于当前协程可能已恢复并执行了等待器对象的析构函数,所有这些都与await_suspend()在当前线程上继续执行同时发生,因此await_suspend()应将*this视为已销毁,并且在句柄发布到其他线程后不应访问它。
[编辑] 示例
#include <coroutine> #include <iostream> #include <stdexcept> #include <thread> auto switch_to_new_thread(std::jthread& out) { struct awaitable { std::jthread* p_out; bool await_ready() { return false; } void await_suspend(std::coroutine_handle<> h) { std::jthread& out = *p_out; if (out.joinable()) throw std::runtime_error("Output jthread parameter not empty"); out = std::jthread([h] { h.resume(); }); // Potential undefined behavior: accessing potentially destroyed *this // std::cout << "New thread ID: " << p_out->get_id() << '\n'; std::cout << "New thread ID: " << out.get_id() << '\n'; // this is OK } void await_resume() {} }; return awaitable{&out}; } struct task { struct promise_type { task get_return_object() { return {}; } std::suspend_never initial_suspend() { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void return_void() {} void unhandled_exception() {} }; }; task resuming_on_new_thread(std::jthread& out) { std::cout << "Coroutine started on thread: " << std::this_thread::get_id() << '\n'; co_await switch_to_new_thread(out); // awaiter destroyed here std::cout << "Coroutine resumed on thread: " << std::this_thread::get_id() << '\n'; } int main() { std::jthread out; resuming_on_new_thread(out); }
可能的输出
Coroutine started on thread: 139972277602112 New thread ID: 139972267284224 Coroutine resumed on thread: 139972267284224
注意:等待器对象是协程状态的一部分(作为生命周期跨越暂停点的临时变量),并在co_await表达式结束前被销毁。它可以用于维护某些异步I/O API所需的操作状态,而无需额外的动态分配。
标准库定义了两个简单的可等待对象:std::suspend_always和std::suspend_never。
本节不完整 原因:示例 |
promise_type::await_transform和程序提供的等待器的演示 |
---|
[编辑] 示例运行此代码 #include <cassert> #include <coroutine> #include <iostream> struct tunable_coro { // An awaiter whose "readiness" is determined via constructor's parameter. class tunable_awaiter { bool ready_; public: explicit(false) tunable_awaiter(bool ready) : ready_{ready} {} // Three standard awaiter interface functions: bool await_ready() const noexcept { return ready_; } static void await_suspend(std::coroutine_handle<>) noexcept {} static void await_resume() noexcept {} }; struct promise_type { using coro_handle = std::coroutine_handle<promise_type>; auto get_return_object() { return coro_handle::from_promise(*this); } static auto initial_suspend() { return std::suspend_always(); } static auto final_suspend() noexcept { return std::suspend_always(); } static void return_void() {} static void unhandled_exception() { std::terminate(); } // A user provided transforming function which returns the custom awaiter: auto await_transform(std::suspend_always) { return tunable_awaiter(!ready_); } void disable_suspension() { ready_ = false; } private: bool ready_{true}; }; tunable_coro(promise_type::coro_handle h) : handle_(h) { assert(h); } // For simplicity, declare these 4 special functions as deleted: tunable_coro(tunable_coro const&) = delete; tunable_coro(tunable_coro&&) = delete; tunable_coro& operator=(tunable_coro const&) = delete; tunable_coro& operator=(tunable_coro&&) = delete; ~tunable_coro() { if (handle_) handle_.destroy(); } void disable_suspension() const { if (handle_.done()) return; handle_.promise().disable_suspension(); handle_(); } bool operator()() { if (!handle_.done()) handle_(); return !handle_.done(); } private: promise_type::coro_handle handle_; }; tunable_coro generate(int n) { for (int i{}; i != n; ++i) { std::cout << i << ' '; // The awaiter passed to co_await goes to promise_type::await_transform which // issues tunable_awaiter that initially causes suspension (returning back to // main at each iteration), but after a call to disable_suspension no suspension // happens and the loop runs to its end without returning to main(). co_await std::suspend_always{}; } } int main() { auto coro = generate(8); coro(); // emits only one first element == 0 for (int k{}; k < 4; ++k) { coro(); // emits 1 2 3 4, one per each iteration std::cout << ": "; } coro.disable_suspension(); coro(); // emits the tail numbers 5 6 7 all at ones } 输出 0 1 : 2 : 3 : 4 : 5 6 7 |
[编辑] co_yield
co_yield
表达式向调用者返回一个值并暂停当前协程:它是可恢复生成器函数的常见构建块。
co_yield expr |
|||||||||
co_yield braced-init-list |
|||||||||
它等同于
co_await promise.yield_value(expr)
典型的生成器的yield_value
会将其参数存储(复制/移动或仅存储地址,因为参数的生命周期会跨越co_await
内部的暂停点)到生成器对象中,并返回std::suspend_always,将控制权转移给调用者/恢复者。
#include <coroutine> #include <cstdint> #include <exception> #include <iostream> template<typename T> struct Generator { // The class name 'Generator' is our choice and it is not required for coroutine // magic. Compiler recognizes coroutine by the presence of 'co_yield' keyword. // You can use name 'MyGenerator' (or any other name) instead as long as you include // nested struct promise_type with 'MyGenerator get_return_object()' method. // (Note: It is necessary to adjust the declarations of constructors and destructors // when renaming.) struct promise_type; using handle_type = std::coroutine_handle<promise_type>; struct promise_type // required { T value_; std::exception_ptr exception_; Generator get_return_object() { return Generator(handle_type::from_promise(*this)); } std::suspend_always initial_suspend() { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void unhandled_exception() { exception_ = std::current_exception(); } // saving // exception template<std::convertible_to<T> From> // C++20 concept std::suspend_always yield_value(From&& from) { value_ = std::forward<From>(from); // caching the result in promise return {}; } void return_void() {} }; handle_type h_; Generator(handle_type h) : h_(h) {} ~Generator() { h_.destroy(); } explicit operator bool() { fill(); // The only way to reliably find out whether or not we finished coroutine, // whether or not there is going to be a next value generated (co_yield) // in coroutine via C++ getter (operator () below) is to execute/resume // coroutine until the next co_yield point (or let it fall off end). // Then we store/cache result in promise to allow getter (operator() below // to grab it without executing coroutine). return !h_.done(); } T operator()() { fill(); full_ = false; // we are going to move out previously cached // result to make promise empty again return std::move(h_.promise().value_); } private: bool full_ = false; void fill() { if (!full_) { h_(); if (h_.promise().exception_) std::rethrow_exception(h_.promise().exception_); // propagate coroutine exception in called context full_ = true; } } }; Generator<std::uint64_t> fibonacci_sequence(unsigned n) { if (n == 0) co_return; if (n > 94) throw std::runtime_error("Too big Fibonacci sequence. Elements would overflow."); co_yield 0; if (n == 1) co_return; co_yield 1; if (n == 2) co_return; std::uint64_t a = 0; std::uint64_t b = 1; for (unsigned i = 2; i < n; ++i) { std::uint64_t s = a + b; co_yield s; a = b; b = s; } } int main() { try { auto gen = fibonacci_sequence(10); // max 94 before uint64_t overflows for (int j = 0; gen; ++j) std::cout << "fib(" << j << ")=" << gen() << '\n'; } catch (const std::exception& ex) { std::cerr << "Exception: " << ex.what() << '\n'; } catch (...) { std::cerr << "Unknown exception.\n"; } }
输出
fib(0)=0 fib(1)=1 fib(2)=1 fib(3)=2 fib(4)=3 fib(5)=5 fib(6)=8 fib(7)=13 fib(8)=21 fib(9)=34
[编辑] 注意
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_impl_coroutine |
201902L |
(C++20) | 协程 (编译器支持) |
__cpp_lib_coroutine |
201902L |
(C++20) | 协程 (库支持) |
__cpp_lib_generator |
202207L |
(C++23) | std::generator:用于范围的同步协程生成器 |
[编辑] 关键字
[编辑] 库支持
协程支持库定义了几种类型,为协程提供编译时和运行时支持。
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
CWG 2556 | C++20 | 无效的return_void 导致协程执行到末尾的行为未定义 |
程序格式错误 在这种情况下,枚举是病态的 |
CWG 2668 | C++20 | co_await不能出现在lambda表达式中 | 允许 |
CWG 2754 | C++23 | 为显式对象成员函数构造promise对象时, 获取*this |
在这种情况下,*this不被 获取 |
[编辑] 另请参阅
(C++23) |
表示同步协程生成器的view (类模板) |
[编辑] 外部链接
1. | Lewis Baker, 2017-2022 - 非对称传输 (Asymmetric Transfer)。 |
2. | David Mazières, 2021 - C++20 协程教程 (Tutorial on C++20 coroutines)。 |
3. | 许川起 & 齐宇 & 韩瑶, 2021 - C++20 协程原理与应用 (C++20 Principles and Applications of Coroutine)。 |
4. | Simon Tatham, 2023 - 编写自定义 C++20 协程系统 (Writing custom C++20 coroutine systems)。 |