std::thread 能不能看做能够暂停执行的函数?
一般认为线程是抢占式的, 协程是协作式的, 所以称为协程
协程是一种能够暂停执行的函数:通过 suspend
操作暂停后,可以在稍后的某个时刻通过 resume
操作继续执行
协程本身不是并发的, worker 对协程的执行可能是并发的
(当然按这个说法 std::thread 本身也不是并发的, 是 CPU
核对线程的执行可能是并发的)
按 控制转移机制 区分, 分为对称协程和非对称协程
按 是否能够在嵌套调用内部 暂停执行 区分,
分为有栈协程和无栈协程
协程之前
可维护性
异步读:
1 2 3 4 5 6 7 8 9 10 11 12 13 void read_data () { async_read (fd, [](auto data) { async_process (data, [](auto result) { async_write (fd, result, [] { async_flush (fd, [] { async_close (fd, [] { }); }); }); }); }); }
1 2 3 4 5 6 task<void > read_data () { auto data = co_await async_read (fd); auto result = co_await async_process (data); co_await async_write (fd, result) ; }
从这个例子来看, 协程的控制权转移和回调是差不多的,
注册回调看做协程注册 handle 的部分, 调用回调看做协程的
handle.resume()
这里体现了协程的一些主要好处:
最后的 完成 部分, 我们仍在初始的 read_data
内部, 这部分所需要的数据不需要一层层传给回调函数
(万一需要的数据变了接口全得改), 而是通过协程帧等方式自动处理
可以随意拆分 read_data; 回调版本只能改接口,
把拆分后的部分再作为回调
当然从理论上讲协程也是通过回调实现的, 所以两者的表达能力是相同的
性能
线程
A context switch between threads requires system calls (involving the
OS kernel), which can cost more than thousand CPU cycles on x86 CPUs. By
contrast, transferring control vias callcc()/continuation requires only
few CPU cycles because it does not involve system calls as it is done
within a single thread.
额外消耗:
用户态内核态切换
内核调度器
可能切换到其他进程的线程导致的 tlb miss
可能被切到其他核
分类
无栈协程 (状态机)
提供三个操作:
create: 创建, 但不执行
resume: 开始执行(转移)
yield: 到达下一个状态, 暂停执行
需要把所有跨越状态使用的变量额外保存在堆上, 实现类似于:
(注意无栈协程的暂停点是编译期确定的,
所以无栈协程可以不保存寄存器)
(如果编译器能确定协程生存期严格嵌入 caller 生存期中, 也可以放在
caller 的栈帧或者协程 frame 中)
1 2 3 4 5 6 Task foo () { int a = 10 ; co_await something () ; int b = a + 1 ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 struct FooFrame { int state; int a; void resume () { switch (state) { case 0 : a = 10 ; state = 1 ; return ; case 1 : int b = a + 1 ; return ; } } };
一个示例
有栈协程
和线程类似, 保存着当前的调用栈 (不管是协程的,
还是协程调用的非协程函数的), 协程暂停时还需要保存寄存器之类的
(更可能需要编译器开洞或者手写汇编)
对称协程
可以将控制权交给任意协程
非对称协程
只能将控制权交给调用者
常见实现
cpp20:
无栈, 对称转移
一般来说, C++ 启动协程后获取这个协程的 handle (或者能拿到协程 promise
的任何东西), 通过协程的 promise 获取实际执行完成的返回值
之所以是一般来说, 是因为 C++ 是自由的
C++ 经常为了解决一个问题, 通过一个特性, 后来因为太自由功能太强大,
这个特性实际用来做的事和原先的问题没什么关系了; 我看协程有这个潜力
在 C++ 看来, 协程就是函数体包含 co_await,
co_yield, co_return 关键字之一的函数 C++
coroutine 是无栈且对称转移的
似乎标准没规定, 但是对于常见的实现,
我们可以认为跨挂起点的局部变量一开始就是分配在协程帧上的,
在协程函数中对他们的操作也是在帧上操作的 (而不是平时在栈上,
挂起后复制到帧里)
promise
(不是 std::promise,
但是在典型协程中使用方式是相似的)
promise 实例的一些方法会在协程调用的一些时机被调用,
用来控制协程的行为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 struct promise { some_handle get_return_object () { return } some_awaiter initial_suspend () noexcept { return {}; } some_awaiter final_suspend () noexcept { return {}; } void return_void (void ) {} void unhandled_exception () {} some_awaiter yield_value (foo_T) {} auto await_transform (some_T&& value) ; static some_handle get_return_object_on_allocation_failure () noexcept ; static void * operator new (std::size_t size) ; static void operator delete (void * ptr) noexcept ; };
协程函数体的一部分会被编译器替换为对协程的 promise 成员函数的调用,
对于一个函数体为 <body-statements> 的协程函数,
其协程体会被变换为大致如下的形式:
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 { co_await promise.initial_suspend (); try { } catch (...) { promise.unhandled_exception (); } FinalSuspend: co_await promise.final_suspend(); }
handle
一般来说协程的返回值继承或持有
coroutine_handle<yourPromise>, 一个非拥有指针,
可以让我们操作协程
coroutine_handle 大概会长这样:
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 namespace std{ template <typename Promise> struct coroutine_handle ; template <> struct coroutine_handle <void > { bool done () const ; void resume () ; void destroy () ; void * address () const ; static coroutine_handle from_address (void * address) ; }; template <typename Promise> struct coroutine_handle : coroutine_handle<void > { Promise& promise () const ; static coroutine_handle from_promise (Promise& promise) ; static coroutine_handle from_address (void * address) ; }; }
co_await
一个一元运算符, 可以作用在一个 Awaitable 上,
代表挂起直到异步操作 Awaitable 完成
Awaitable 是要 co_await 的目标,
主要逻辑在其 await_suspend 中; 当前协程的 handle 会被传递给
Awaitable 的 await_suspend 的参数,
当前的函数栈就会被销毁, handle 作为和异步操作的联系,
供后来找到当前协程帧并恢复执行
Awaitable: 能被 co_await 调用的类型
(可能通过 operator co_await() 返回另一个
Awaiter, 所以不一定是一个 Awaiter)
Awaiter: 实现下列接口的类型 (一个 Awaiter
一定是一个 Awaitable): 这些接口允许程序员做一些自定义操作
await_ready(): 判断是否需要挂起时调用的回调函数,
避免下面 <suspend-coroutine> 操作的开销
await_suspend(std::coroutine_handle<>):
挂起时调用的回调函数, 传入执行 co_await 表达式的协程的
handle, 返回 bool 或 void (代表是否一定挂起);
一般用来启动异步操作, 且负责在异步操作结束后恢复当前的协程,
比如注册回调函数调用 handle 的 resume, 或者把 handle 扔给调度器
返回 bool: true 代表真的挂起, 否则继续执行
co_await 后面的代码; 避免 await_ready 到
await_suspend 之间的部分状态发生了变化
返回 void: 一定挂起
await_resume(): 恢复时调用的回调函数, 其返回值就是整个
co_await <expr> 的返回值; 如果抛出异常就从
co_await 传播出去
非对称转移的 co_await <expr> 流程如下:
获取 Awaitable: 如果协程 的 promise 有
await_transform 方法, 就通过
promise.await_transform(<expr>) 获取; 否则把
<expr> 本身作为 Awaitable
获取 Awaiter: 如果 Awaitable 有 operator co_await()
方法, 就用这个获取 Awaiter; 否则把 Awaitable 作为 Awaiter
挂起
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 { auto && value = ; auto && awaitable = get_awaitable (promise, static_cast <decltype (value)>(value)); auto && awaiter = get_awaiter (static_cast <decltype (awaitable)>(awaitable)); if (!awaiter.await_ready ()) { using handle_t = std::experimental::coroutine_handle<P>; using await_suspend_result_t = decltype (awaiter.await_suspend (handle_t ::from_promise (promise))); if constexpr (std::is_void_v<await_suspend_result_t >) { awaiter.await_suspend (handle_t ::from_promise (promise)); } else { static_assert ( std::is_same_v<await_suspend_result_t , bool >, "await_suspend() must return 'void' or 'bool'." ); if (awaiter.await_suspend (handle_t ::from_promise (promise))) { } } } return awaiter.await_resume (); }
注意 <return-to-caller-or-resumer> 后这个 “栈”
就销毁了, 恢复时从 <resume-point>
所需要的内容就保存在协程帧里了
快速安全切换协程 worker
可以注意到 await_suspend 是在 协程挂起之后,
转移控制权之前 调用的
有一种 trick 用法是 Awaiter
对象在协程已经挂起之后启动异步操作, 并把已挂起协程的
coroutine_handle 传给该操作; 操作完成时
(可能在另一个线程上), 它可以直接安全地恢复协程, 不需要任何额外的同步
这种用法需要注意: 在传递完 handle 后, await_suspend
就要避免访问 this 和 promise; 因为在 交出 handle 之后,
await_suspend 结束之前, 协程就可能已经恢复了, 这时整个
Awaiter 对象都已经被析构了
还是太 trick 了, 尽量少用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Time Thread 1 Thread 2 | -------- -------- | .... Call OS - Wait for I/O event | Call await_ready() | | <await-ready> | | Call await_suspend(handle) | | Store handle in operation | V Start AsyncFileRead ---+ V +-----> Load coroutine_handle from operation Call handle.resume() Call to await_resume() execution continues.... Call to AsyncFileRead returns Call to await_suspend() returns
有栈协程就很难做到这一点: 大部分有栈协程框架中,
一个协程的挂起与另一个协程的恢复被合并成一次 “上下文切换”; 在这种
“上下文切换” 中一般没有机会在
挂起当前协程之后、把执行权转移给另一个协程之前 执行逻辑
如果我们想在有栈协程上实现类似的异步文件读操作,
就必须在挂起协程之前 启动操作; 而操作有可能在
协程挂起、具备恢复资格 之前 就在另一个线程上完成,
这时调用恢复就会存在竞争, 需要线程同步
参考
还有一个有趣的内存分配优化:
内存分配优化
考虑传统 callback 方式的异步调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 struct ReadOperation { OVERLAPPED overlapped; char buffer[4096 ]; }; void async_read () { auto * op = new ReadOperation (); ReadFile ( file, op->buffer, sizeof (op->buffer), nullptr , &op->overlapped ); }
并发高的情况下会产生大量的堆分配和释放
考虑协程的情况:
1 2 3 4 5 6 7 8 9 10 Task read_async () { ReadOperation op; co_await async_read (file, op) ; }
更好的方法可以把只有异步操作需要的内存放在 Awaiter
里:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 struct ReadAwaiter { OVERLAPPED overlapped; char buffer[4096 ]; bool await_ready () noexcept { return false ; } void await_suspend (std::coroutine_handle<> h) { } void await_resume () noexcept { } }; Task read_async () { co_await ReadAwaiter{}; }
注意 Awaiter 跨越了调用点, 也需要保存在协程帧中;
op 在异步操作完成后, 随着 Awaiter
的销毁而被销毁, 协程帧的空闲空间可以留给下一次挂起使用
其实就是类似手动的
1 2 3 4 5 6 Task read_async () { { ReadOperation op; co_await async_read (file, op) ; } }
吧?
参考
co_yield
co_yield <expr>: 向 promise 中产生值
<expr> 并挂起
实现上基本就是
co_await promise.yield_value(<expr>)
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 #include <coroutine> #include <iostream> struct Generator { struct promise_type { int value; Generator get_return_object () { return Generator{ std::coroutine_handle<promise_type>::from_promise (*this ) }; } std::suspend_always initial_suspend () noexcept { return {}; } std::suspend_always final_suspend () noexcept { return {}; } std::suspend_always yield_value (int v) noexcept { value = v; return {}; } void return_void () {} void unhandled_exception () { std::terminate (); } }; using handle_type = std::coroutine_handle<promise_type>; handle_type handle; explicit Generator (handle_type h) : handle(h) { } ~Generator () { if (handle) { handle.destroy (); } } bool next () { if (!handle || handle.done()) { return false ; } handle.resume (); return !handle.done(); } int value () const { return handle.promise ().value; } }; Generator generate () { co_yield 10 ; co_yield 20 ; co_yield 30 ; } int main () { Generator gen = generate (); while (gen.next ()) { std::cout << gen.value () << '\n' ; } }
co_return
实现上基本就是 1 2 3 promise.return_void(); co_await promise.final_suspend();
对称转移
考虑一个朴素 协程执行器的实现
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 #include <experimental/coroutine> #include <iostream> using namespace std::experimental;class task {public : class promise_type { public : task get_return_object () noexcept { return task{coroutine_handle<promise_type>::from_promise (*this )}; } suspend_always initial_suspend () noexcept { return {}; } void return_void () noexcept {} void unhandled_exception () noexcept { std::terminate (); } struct final_awaiter { bool await_ready () noexcept { return false ; } void await_suspend (coroutine_handle<promise_type> h) noexcept { h.promise ().continuation.resume (); } void await_resume () noexcept {} }; final_awaiter final_suspend () noexcept { return {}; } coroutine_handle<> continuation; }; task (task&& t) noexcept : coro_ (std::exchange (t.coro_, {})) {} ~task () { if (coro_) coro_.destroy (); } class awaiter { public : bool await_ready () noexcept { return false ; } void await_suspend (coroutine_handle<> continuation) noexcept { coro_.promise ().continuation = continuation; coro_.resume (); } void await_resume () noexcept {} private : friend task; explicit awaiter (coroutine_handle<promise_type> h) noexcept : coro_(h) { } coroutine_handle<promise_type> coro_; }; awaiter operator co_await () && noexcept { return awaiter{coro_}; } private : explicit task (coroutine_handle<promise_type> h) noexcept : coro_(h) { } coroutine_handle<promise_type> coro_; }; struct sync_wait_task { struct promise_type { sync_wait_task get_return_object () noexcept { return sync_wait_task{coroutine_handle<promise_type>::from_promise (*this )}; } suspend_never initial_suspend () noexcept { return {}; } suspend_always final_suspend () noexcept { return {}; } void return_void () noexcept {} void unhandled_exception () noexcept { std::terminate (); } }; coroutine_handle<promise_type> coro_; explicit sync_wait_task (coroutine_handle<promise_type> h) noexcept : coro_(h) { } sync_wait_task (sync_wait_task&& t) noexcept : coro_ (t.coro_) { t.coro_ = {}; } ~sync_wait_task () { if (coro_) { coro_.destroy (); } } static sync_wait_task start (task&& t) { co_await std::move (t) ; } bool done () { return coro_.done(); } }; struct manual_executor { struct schedule_op { manual_executor& executor_; schedule_op* next_ = nullptr ; coroutine_handle<> continuation_; schedule_op (manual_executor& executor) : executor_ (executor) {} bool await_ready () noexcept { return false ; } void await_suspend (coroutine_handle<> continuation) noexcept { continuation_ = continuation; next_ = executor_.head_; executor_.head_ = this ; } void await_resume () noexcept {} }; schedule_op* head_ = nullptr ; schedule_op schedule () noexcept { return schedule_op{*this }; } void drain () { while (head_ != nullptr ) { auto * item = head_; head_ = item->next_; item->continuation_.resume (); } } void sync_wait (task&& t) { auto t2 = sync_wait_task::start (std::move (t)); while (!t2.done()) { drain (); } } }; task foo (manual_executor& ex) { std::cout << "inside foo()\n" ; co_await ex.schedule (); std::cout << "about to return from foo()\n" ; co_return ; } task bar (manual_executor& ex) { std::cout << "about to call foo()\n" ; co_await foo (ex) ; std::cout << "done calling foo()\n" ; } int main () { manual_executor ex; ex.sync_wait (bar (ex)); return 0 ; }
真是一场酣畅淋漓的赤石啊, 控制权到处乱飞 资源管理心惊肉跳给人一种
goto 领域大神的感觉
栈溢出
我们可以注意到, 在上面的实现中, await foo()
执行完成开始销毁的时候, 控制权在 foo 和 bar
之间来回横跳
考虑下面的执行过程:
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 task completes_synchronously () { co_return ; } task loop_synchronously (int count) { std::cout << "loop_synchronously(" << count << ")" << std::endl; for (int i = 0 ; i < count; ++i) { co_await completes_synchronously () ; } std::cout << "loop_synchronously(" << count << ") returning" << std::endl; } int main () { manual_executor ex; ex.sync_wait (loop_synchronously (100 )); ex.sync_wait (loop_synchronously (1000 )); ex.sync_wait (loop_synchronously (100'000 )); ex.sync_wait (loop_synchronously (1'000'000 )); return 0 ; }
朴素解法
TODO
要用原子变量, 有额外同步消耗
返回 handle
进入正题, 对称转移
允许 await_suspend 返回一个
std::coroutine_handle<>
co_await 流程变为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 { decltype (auto ) value = <expr>; decltype (auto ) awaitable = get_awaitable (promise, static_cast <decltype (value)&&>(value)); decltype (auto ) awaiter = get_awaiter (static_cast <decltype (awaitable)&&>(awaitable)); if (!awaiter.await_ready ()) { using handle_t = std::coroutine_handle<P>; auto h = awaiter.await_suspend (handle_t ::from_promise (p)); h.resume (); } return awaiter.await_resume (); }
总的来说, 如果把 resume 也看做调用, 协程在 await_suspend 执行结束后,
co_await 的非对称形式从调用者调用完成的位置继续执行, 对称形式从
await_suspend 返回的 handle 代表的协程的挂起位置继续执行
由于 <return-to-caller-or-resumer> 时,
当前的函数调用栈已经被销毁了, 所以 h.resume()
就是函数调用中的最后一个操作了, 即 “尾调用”
尾调用
尾调用可以复用当前的函数调用栈, 如果:
调用约定支持尾调用, 且调用方与被调用方一致: body 部分的 abi
由编译器决定, 编译器可以构造一个一致且支持尾调用的
返回类型相同: 都是 void
调用之后、返回给调用方之前没有需要运行的非平凡析构函数:
在调用下一个协程的 resume 之前, 栈上的对象都析构完了,
协程帧上的不用析构
调用不在 try/catch 块内: 如果看 promise 那一节的伪代码可能觉得在 try
内, 但是实际实现时为了规避这个问题把 h.resume 挪出去了
所以对于对称转移的协程, 这些条件都满足
使用对称转移改造后, 代码如下
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 #include <experimental/coroutine> #include <iostream> using namespace std::experimental;class task {public : class promise_type { public : task get_return_object () noexcept { return task{coroutine_handle<promise_type>::from_promise (*this )}; } suspend_always initial_suspend () noexcept { return {}; } void return_void () noexcept {} void unhandled_exception () noexcept { std::terminate (); } struct final_awaiter { bool await_ready () noexcept { return false ; } coroutine_handle<> await_suspend (coroutine_handle<promise_type> h) noexcept { return h.promise ().continuation; } void await_resume () noexcept {} }; final_awaiter final_suspend () noexcept { return {}; } coroutine_handle<> continuation; }; task (task&& t) noexcept : coro_ (std::exchange (t.coro_, {})) {} ~task () { if (coro_) coro_.destroy (); } class awaiter { public : bool await_ready () noexcept { return false ; } coroutine_handle<> await_suspend (coroutine_handle<> continuation) noexcept { coro_.promise ().continuation = continuation; return coro_; } void await_resume () noexcept {} private : friend task; explicit awaiter (coroutine_handle<promise_type> h) noexcept : coro_(h) { } coroutine_handle<promise_type> coro_; }; awaiter operator co_await () && noexcept { return awaiter{coro_}; } private : explicit task (coroutine_handle<promise_type> h) noexcept : coro_(h) { } coroutine_handle<promise_type> coro_; }; struct sync_wait_task { struct promise_type { sync_wait_task get_return_object () noexcept { return sync_wait_task{coroutine_handle<promise_type>::from_promise (*this )}; } suspend_never initial_suspend () noexcept { return {}; } suspend_always final_suspend () noexcept { return {}; } void return_void () noexcept {} void unhandled_exception () noexcept { std::terminate (); } }; coroutine_handle<promise_type> coro_; explicit sync_wait_task (coroutine_handle<promise_type> h) noexcept : coro_(h) { } sync_wait_task (sync_wait_task&& t) noexcept : coro_ (t.coro_) { t.coro_ = {}; } ~sync_wait_task () { if (coro_) { coro_.destroy (); } } static sync_wait_task start (task&& t) { co_await std::move (t) ; } bool done () { return coro_.done(); } }; struct manual_executor { struct schedule_op { manual_executor& executor_; schedule_op* next_ = nullptr ; coroutine_handle<> continuation_; schedule_op (manual_executor& executor) : executor_ (executor) {} bool await_ready () noexcept { return false ; } void await_suspend (coroutine_handle<> continuation) noexcept { continuation_ = continuation; next_ = executor_.head_; executor_.head_ = this ; } void await_resume () noexcept {} }; schedule_op* head_ = nullptr ; schedule_op schedule () noexcept { return schedule_op{*this }; } void drain () { while (head_ != nullptr ) { auto * item = head_; head_ = item->next_; item->continuation_.resume (); } } void sync_wait (task&& t) { auto t2 = sync_wait_task::start (std::move (t)); while (!t2.done()) { drain (); } } }; task completes_synchronously () { co_return ; } task loop_synchronously (int count) { std::cout << "loop_synchronously(" << count << ")" << std::endl; for (int i = 0 ; i < count; ++i) { co_await completes_synchronously () ; } std::cout << "loop_synchronously(" << count << ") returning" << std::endl; } int main () { manual_executor ex; ex.sync_wait (loop_synchronously (100 )); ex.sync_wait (loop_synchronously (1000 )); ex.sync_wait (loop_synchronously (100'000 )); ex.sync_wait (loop_synchronously (1'000'000 )); return 0 ; }
调用过程中的栈帧图可以参考
对称转移可以实现非对称转移
显然, 从定义来看, 转移给任意协程包括转移给调用者
只需要 await_suspend 返回
std::noop_coroutine() (通常的实现就是只包含 ret) 就行了
例 1
1 2 3 4 void my_awaiter::await_suspend (std::coroutine_handle<> h) { this ->coro = h; enqueue (this ); }
1 2 3 4 5 bool my_awaiter::await_suspend (std::coroutine_handle<> h) { this ->coro = h; enqueue (this ); return true ; }
1 2 3 4 5 6 std::noop_coroutine_handle my_awaiter::await_suspend ( std::coroutine_handle<> h) { this ->coro = h; enqueue (this ); return std::noop_coroutine (); }
例 2
1 2 3 4 5 6 7 8 9 10 11 12 13 bool my_awaiter::await_suspend (std::coroutine_handle<> h) { this ->coro = h; if (try_start(this )) { return true ; } return false ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 std::coroutine_handle<> my_awaiter::await_suspend (std::coroutine_handle<> h) { this ->coro = h; if (try_start(this )) { return std::noop_coroutine (); } return h; }
编译器转换
TODO
最佳实践?
总的来说, C++ 是自由的
可惜程序员不是, 所以找点最佳实践洗洗眼睛
TODO
python
无栈, 非对称转移
不能自定义协程返回 handle 的是不是基本都是非对称的
async def 返回 handle, 可以对 handle 进行:
asyncio.run(handle): 有点类似 cuda 里的
__global__, 用来作为桥梁在普通函数中启动协程
await: 只能在 async def 的函数中执行;
挂起当前协程, 等待 await 的协程结束后继续执行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import asyncioimport timeasync def say_after (delay, what ): await asyncio.sleep(delay) print (what) async def main (): print (f"started at {time.strftime('%X' )} " ) await say_after(1 , 'hello' ) await say_after(2 , 'world' ) print (f"finished at {time.strftime('%X' )} " ) asyncio.run(main())
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 async def main (): task1 = asyncio.create_task( say_after(1 , 'hello' )) task2 = asyncio.create_task( say_after(2 , 'world' )) print (f"started at {time.strftime('%X' )} " ) await task1 await task2 print (f"finished at {time.strftime('%X' )} " )
python 还能 await 一个 future, 类似 future.get
的异步版本
loop
TODO
bthread
有栈, 非对称转移
虽然日常说法都把 bthread 当做协程
但是 bthread 第一个
faq 就说他不是协程
为什么?
bthread 定义的协程似乎是每个线程上有一个任务队列,
一个任务分配到一个线程就只能在这个线程执行了,
这个线程可以切换在这个线程上的任务? 可能是定义年代问题吧, 不然 cpp 的
coroutine 恐怕都不算协程了
bthread 有调度器? 但是似乎日常也把 goroutine 看做协程?
注意其中所谓的 “一个bthread被卡住不会影响其他bthread”
只能说不会卡死所有 bthread, 执行效率依然下降了 (少了一个 worker)
操作:
bthread_start_background: 在后台启动新 bthread
bthread_start_urgent: 挂起当前 bthread, 后台启动新
bthread 并立刻执行这个新 bthread
bthread_yield(): 挂起
return: 销毁
bthread 提供的非阻塞操作: bthread_usleep,
bthread_cond_wait …
bthread 操作的一个好处在于可以在 bthread 上进行也可以在 pthread
上进行, bthread 上表现为非阻塞操作 (对 worker 来说), pthread
上表现为阻塞操作
注意虽然 bthread 只在这些非阻塞函数上表现为协程 (可以挂起),
但这个挂起可以让上层的非协程函数也跟着挂起 (表现为有栈); 对比 cpp20
的协程如果想让上层跟着挂起, 上层必须是个协程 (包含
co_await)
bthread 的函数调用栈类似于多线程时不同线程的栈,
挂起时的寄存器用汇编压到 bthread 自己的栈上,
恢复时再用汇编弹回寄存器上
注意到 bthread 的启动方式导致 bthread
的函数调用栈和创建者的函数调用栈没有关系
Boost.Context
fiber
有栈, 对称转移
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 namespace ctx=boost::context;int a;ctx::fiber source{[&a](ctx::fiber&& sink){ a=0 ; int b=1 ; for (;;){ sink=std::move (sink).resume (); int next=a+b; a=b; b=next; } return std::move (sink); }}; for (int j=0 ;j<10 ;++j) { source=std::move (source).resume (); std::cout << a << " " ; }
参数
参数只能通过捕获, 全局变量, std::bind 传递; 有点麻烦
1 2 3 4 5 6 7 8 9 10 11 12 13 ctx::fiber generate (int & a, ctx::fiber&& sink) { a = 0 ; int b = 1 ; for (;;) { sink = std::move (sink).resume (); int next = a + b; a = b; b = next; } return std::move (sink); }
ctx::fibre 的构造函数只接受签名为
fiber(fiber && f) 的 callable
所以要包装一层:
1 2 3 4 5 int a;ctx::fiber source{ std::bind (generate, std::ref (a), std::placeholders::_1) };
注入
resume_with 可以在对方的栈上执行代码, 挺有意思的
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 namespace ctx=boost::context;int data=0 ;ctx::fiber f1{[&data](ctx::fiber&& f2) { std::cout << "f1: entered first time: " << data << std::endl; data+=1 ; f2=std::move (f2).resume (); std::cout << "f1: entered second time: " << data << std::endl; data+=1 ; f2=std::move (f2).resume (); std::cout << "f1: entered third time: " << data << std::endl; return std::move (f2); }}; f1=std::move (f1).resume (); std::cout << "f1: returned first time: " << data << std::endl; data+=1 ; f1=std::move (f1).resume (); std::cout << "f1: returned second time: " << data << std::endl; data+=1 ; f1=std::move (f1).resume_with ([&data](ctx::fiber&& f2){ std::cout << "f2: entered: " << data << std::endl; data=-1 ; return std::move (f2); }); std::cout << "f1: returned third time" << std::endl;
在谁的栈上执行有区别吗?
比较简单的例子就是异常处理:
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 namespace ctx=boost::context;struct my_exception : public std::runtime_error { ctx::fiber f; my_exception (ctx::fiber&& f_,std::string const & what) : std::runtime_error{ what }, f{ std::move (f_) } { } }; ctx::fiber f{[](ctx::fiber && f) ->ctx::fiber { std::cout << "entered" << std::endl; try { f=std::move (f).resume (); } catch (my_exception & ex) { std::cerr << "my_exception: " << ex.what () << std::endl; return std::move (ex.f); } return {}; }); f=std::move (f).resume (); f=std::move (f).resume_with ([](ctx::fiber && f) ->ctx::fiber { throw my_exception (std::move (f),"abc" ); return {}; });
callcc & continuation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 namespace ctx=boost::context;int a;ctx::continuation source=ctx::callcc ( [&a](ctx::continuation && sink){ a=0 ; int b=1 ; for (;;){ sink=sink.resume (); int next=a+b; a=b; b=next; } return std::move (sink); }); for (int j=0 ;j<10 ;++j) { std::cout << a << " " ; source=source.resume (); }
Boost.Coroutine
有栈,
Boost.Coroutine2
有栈, 非对称转移
goroutine
有栈, 非对称转移
goroutine 的栈可以动态扩缩容, 不像多线程 / bthread 的栈,
超大小了就栈溢出了
M 可以看做 pthread, 只负责执行
P 看做调度单位, 有任务队列等, 最多绑定一个 M
G 就是 task, 一个 Goroutine
M 数量一般大于 P, 多出来的 M 用来:
M 阻塞时可以解绑其上的 P, 绑定到空闲的其他 M 上, 避免阻塞整个 P
队列中的其他任务; 阻塞的任务完成后就像新加入一个任务一样分配到一个 P
上
这样可以利用原先的阻塞 api, 很简单, 很爽
(也有非阻塞的操作比如等 channel 之类的可以主动让出 P)
需要额外开销, 但是感觉对于有 runtime 的语言来说, 应该就是最优解了
typescript
无栈, 非对称转移