2019.8开始参与我司的一个c++项目,要用协程解决一些问题。之前对c++协程只是很浅薄的了解,此篇文章就是我以疾风扫落叶之势,快速从业界giants吸收对协程的理解。由于是学习或翻译别人的,我只是把这个当成是笔记,不算是我个人的创作。

由于是分别扫的,并未归纳总结在一块,某些描述可能过时,可能重复;笔记根据个人基础程度有侧重,他人阅读可能较突兀。日后待有积累了再做细致总结。
以下有时把协程简写成coro


首先推荐Lewis Baker的四篇介绍文章,很系统化地入门

coroutine theory, Lewis Baker, 2017

不管是普通routine还是coro,在Call操作时,都会生成一个叫做activation frame(不知这个名词是不是通用的?但是确有很多作者使用这个术语)的结构,用以保存状态

You can think of these pieces of information together as describing the ‘continuation’ of the function-call. ie. they describe which invocation of which function should continue executing at which point when this function completes

coroutine的栈桢分配在哪?

由于coro可以被挂起而其frame不被销毁,那就意味着frame不能像通常那样分配在栈上了,而是在堆上。如果编译器能确保coro的frame能完全嵌套在caller的frame里,那么也可以不动态分配在堆上,直接分配在caller的frame里;

coco栈可以分成两个部分,一个是纯粹的stack,叫stack frame, 在coco执行期间才有用(比如一个变量的定义和使用都在suspension point之前,没有跨suspend),另一种是suspend时要保存下来以供后续访问的,可以称为coroutine frame【感觉这两个名称起得还是有些歧义】

在coro TS中,有两个关键字会产生suspend-points, co_await, co_yield. 当coro碰到这两个key words时,它要做以下事情为保存其恢复点作准备:
1. reg中的值要写入coro frame
2. suspend-point位置要写入frame,以下次再恢复;或者未来被destroy时让其知道哪些变量in scope,需要被销毁

Resume Op
caller调用coroutine_handle.resume就可恢复coro的运行,但进入coro之前,要先保存caller的返回地址在新的stack frame(正常的函数调用都会有个stack frame)里,再跳向coro frame里上次保存的resume-point

Destroy Op
只能对suspended coro做destroy操作;
同resume一样,destroy操作也要分配新的stack frame装caller的返回地址;但是coro不再从suspend-point处开始走,而是走到另外一条路径上,用于销毁suspend-point处in-scope的变量

Call Op
从caller的角度看,call coro 与call normal-function没有区别。当执行call op on a coroutine时,caller要分配新的stack frame,将参数和return address写进去;
然后,将stack frame拷贝或move到coro frame,这样上一次suspend的状态才能得以延续

The first thing the coroutine does is then allocate a coroutine-frame on the heap and copy/move the parameters from the stack-frame into the coroutine-frame so that the lifetime of the parameters extends beyond the first suspend-point.

Call 有什么关键字来表现其是Call op ? Return至少还有co_return

**
co_return与正常函数返回有点不一样,它把返回值存在可自定义的地方,然后有机会执行一些额外逻辑(如final_suspend)来结束自己或者通知其它coro,这是可以定制的;

接着协程可以执行Suspend or Destroy(return后难道还会回来?),执行就返回到caller/resumer

图形化解释

很形象!我们可得知,编译器可能会用单独的reg来指向coro frame,如MSVC使用rbp

When the coroutine suspends for the first time, a return-value is returned to the caller. This return value often holds a handle to the coroutine-frame that suspended that can be used to later resume it.

当协程第一次被挂起时,会返回一个coroutine_handle给caller,这样下次可以用它来恢复

When x() suspends it also stores the address of the resumption-point of x() in the coroutine frame (call it RP for resume-point)

协程挂起时,恢复点保存在RP(resume-point)里

不过这里有点奇怪,本身之前是rbp指向coro frame,suspend后,竟然是caller里的handle指向coro frame 【这种改变过于突兀吧】
image.png

suspend后,即将执行f()
image.png

这个handle现在可以按需传递了,可以传到另外一个线程里进行resume(图里的h()很可能就是另外一个stack了,和之前的f()不处一块),这样就激活了协程的coroutine-frame,从resume-point处继续执行

co_await机制, Lewis Baker, 2017

TS库提供的是很底层的机制,不容易直接使用,需要库开发者建立更高层的抽象,方便应用开发者使用;

coroutine TS并未定义协程的语义,它只是定义了一种通用机制,库开发者可以用定义TS提供的接口来实现不同类型的协程。有两种接口定义,Promise接口和Awaitable接口。此篇只讲Awaitable

co_await只能在coroutine上下文里使用,使用co_await的函数body都会被编译成coroutine;
支持co_wait操作符的type叫做Awaitable type; 而Awaiter type实现了以下三种方法:
await_ready, await_suspend, await_resume

一个类型可以同时是Awaitable和Awaiter; 当编译器看到co_await 时,根据所涉及到的类型会有不同的事情发生;

假设awaiting的Coro对应的promise type是P,其左值引用是promise, 如果P有await_transform方法,则expr首先被传到:promise.await_tranform(),这样能获得一个Awaitable value, awaitable;否则就直接被evaluated 成一个Awaitable;

然后对于获得的awaitable,如果其类型重载了co_await方法,则调用它以获得awaiter对象,否则此awaitable就是awaiter;

以上逻辑可翻译成以下伪代码:

  1. template<typename P, typename T>
  2. decltype(auto) get_awaitable(P& promise, T&& expr)
  3. {
  4. if constexpr (has_any_await_transform_member_v<P>)
  5. return promise.await_transform(static_cast<T&&>(expr));
  6. else
  7. return static_cast<T&&>(expr);
  8. }
  9. template<typename Awaitable>
  10. decltype(auto) get_awaiter(Awaitable&& awaitable)
  11. {
  12. if constexpr (has_member_operator_co_await_v<Awaitable>)
  13. return static_cast<Awaitable&&>(awaitable).operator co_await();
  14. else if constexpr (has_non_member_operator_co_await_v<Awaitable&&>)
  15. return operator co_await(static_cast<Awaitable&&>(awaitable));
  16. else
  17. return static_cast<Awaitable&&>(awaitable);
  18. }

然后,co_await 对应底层的代码大概是这样:

  1. {
  2. auto&& value = <expr>;
  3. auto&& awaitable = get_awaitable(promise, static_cast<decltype(value)>(value));
  4. auto&& awaiter = get_awaiter(static_cast<decltype(awaitable)>(awaitable));
  5. if (!awaiter.await_ready())
  6. {
  7. using handle_t = std::experimental::coroutine_handle<P>;
  8. // 注意这里的await_suspend并不会被执行,只是取其返回类型而已
  9. using await_suspend_result_t =
  10. decltype(awaiter.await_suspend(handle_t::from_promise(p)));
  11. <suspend-coroutine>
  12. if constexpr (std::is_void_v<await_suspend_result_t>)
  13. {
  14. awaiter.await_suspend(handle_t::from_promise(p));
  15. <return-to-caller-or-resumer>
  16. }
  17. else
  18. {
  19. static_assert(
  20. std::is_same_v<await_suspend_result_t, bool>,
  21. "await_suspend() must return 'void' or 'bool'.");
  22. if (awaiter.await_suspend(handle_t::from_promise(p)))
  23. {
  24. <return-to-caller-or-resumer>
  25. }
  26. }
  27. <resume-point>
  28. }
  29. return awaiter.await_resume();
  30. }

返回bool的await_suspend可用于以下场合:awaiter发起了一个本可以同步执行的异步操作,此时若await_suspend返回false,则表明此coro可立刻执行;

在处,代表着编译器生成一些代码来保存coro状态(包括保存resume-point, 寄存器等);且等它返回就可认为当前coro已经suspended

The current coroutine is considered suspended after the operation completes

await_ready是用来表示:如果你知道操作将很快完成,就没有必要进行一系列的保存和恢复工作了(也就没有必要suspend coro),直接跑;

在那,就会弹出当前coro的stack frame,但保留其coro frame;

return await_resume()返回的结果就是 **co_await <expr>** 最终的结果;当然它也可传出异常;
如果异常从 await_suspend 中抛出,则自动resume且不再调用 await_resume

当实现awaitable类型时,一个关键方法是coroutine_handle的resume方法。调用h.resume可激活在处的coro,当那个被激活的coro再次遇到时,resume才返回;

address/to_address往往是用来与c api交互的,但作者习惯将coroutine_handle封装在一个struct,然后将struct指针放进c api的context中;

勿需同步的异步代码

One of the powerful design-features of the co_await operator is the ability to execute code after the coroutine has been suspended but before execution is returned to the caller/resumer.

可以把handle传给另一个线程,让其在IO操作完成后resume
image.png

对比stackful coroutine

像win 32 fiber, boost context的stackful coro,通过上下文切换来suspend/resume coro,但这样就无法在suspend current coro和resume another coro之间添加额外逻辑;(为什么这么需要在这之间添加逻辑?)

也就意味着如果stackful coro要实现async file op,则需在suspend current coro之前发起操作,那如果此操作在另一线程上迅速完成,则本可以恢复的current coro却被suspend了;解决它需要某种形式的线程同步

内存开销

传统上异步操作时,状态往往需要被保存直至操作完成;
但在这里,我们可以把per-operation state放进awaiter中,跟随上下文被保存在coro frame里

By placing the per-operation state in the Awaiter object we can effectively “borrow” memory from the coroutine frame for storing the per-operation state for the duration of the co_await expression

一次堆分配,coro-frame就可以用于许多asnc op

可以把coro frame看成是一个高性能的arena memory allocator

example:一个简单的线程同步primitive

https://godbolt.org/g/Ad47tH

Understanding the promise type,Lewis Baker, 2018

https://lewissbaker.github.io/2018/09/05/understanding-the-promise-type

promise objects

作者首先强调,不要把coro的promise与future的promise混为一谈,虽说前者有后者的影子,但概念上基本不相通,应该把前者看成是跟踪coro状态的数据结构【强调这一点特别好,很多作者讲协程没有对此概念加以澄清】

Promise接口定义了一些方法,可以定制coro本身的行为,library writer可以定制协和在调用时做什么,在返回时做什么,也可以定制 co_await, co_yield表达式的行为;(这其实就相当于hook函数,允许上层改变行为)

Promise object的创建是在coro frame里,当coro func被调用时; 编译器为promise obj生成相应的方法,在coro的关键执行点处调用;

当我们写一个coro function,带有body,里面包含 co_return, co_await, co_yield 等时,代码会被大致翻译成如下样子:

  1. {
  2. co_await promise.initial_suspend();
  3. try
  4. {
  5. <body-statements>
  6. }
  7. catch (...)
  8. {
  9. promise.unhandled_exception();
  10. }
  11. FinalSuspend:
  12. co_await promise.final_suspend();
  13. }

在真正执行body前,有如下动作要做:

  1. 用operator new 分配coro frame
  2. copy any function parameters to coro frame
  3. Call the ctor for promise object
  4. Call promise.get_return_object()
  5. 。。。

这些细节肯定记了又忘,关键还是记住整体的设计和使用方法!

编译器如何处理coro 函数

分配coro frame
传给operator new的size不是sizeof(Promise),而是整个coro frame大小,由编译器自动获取;

编译器可以在在合适的时候避免调用operator new,当

  • 编译器能够确定coro frame的life time被严格限定在caller 的lifetime内
  • 编译器在调用处获得coro frame 大小?

但TS尚未显示有allocation elision的案例;
哪怕定制了memory allocator,编译器也是可以elide的;

copying parameters to coro frame
通过coro func传过来的参数,要放在coro frame中保存。此时注意参数是by value, by lref, by rref,是有不同影响的

Constructing the promise obj
先拷贝参数,再构建 promise就可使得promise可以访问被传递的参数

Obtaining the return obj
首先调用 promise.get_return_object() ,它的值会在coro 第一次suspend或运行结束时,返回给caller的;
需要在执行coro body前获得 return-object,因为

since the coroutine frame (and thus the promise object) may be destroyed prior to the call to coroutine_handle::resume() returning, either on this thread or possibly on another thread, and so it would be unsafe to call get_return_object() after starting execution of the coroutine body

initial_suspend point
接下来,执行 co_await promise.initial_suspend() ; 以允许Promise type控制是否要suspend coro

对大多数 coro, initial_suspend 要么返回 suspend_always, 要么 suspend_never

returning to the caller
当coro func 第一次碰到 return-to-caller-or-resumer 点时,从 get_return_object() 返回的对象被返回到 caller; 此对象的 type 不一定得跟 coro func的return-type一致,会有隐式转换

Returning from coro using co_return
当coro 遇到 co_return 时,根据以下规则 转换:

  • co_return -> promise.return_void()
  • co_return -> promise.return_void() if has type void, otherwise promise.return_value()

之后有 goto FinalSuspend; 将会导致所有的局部变量销毁,然后执行 co_await promise.final_suspend
如果协程函数最后没有用co_return,则默认是有的

处理从协程中传出的异常
如果从 coro body中抛出异常,则异常会 promise.unhandled_exception() 会在catch中被调用,此调用一般会调 std::current_exception() 获得一份异常拷贝在另外的ctx再rethrow

作者认为 尽量不要在inital_suspend, final_suspend, unhandled_exception等中抛出异常

final-suspend point
当执行离开coro body,且结果被return_void() , return_value() 捕获后,coro有机会再执行额外逻辑,即可执行 co_await promise.final_suspend()

建议在final_suspend处suspend,这样有助于编译器判断coro frame的生命期,以此可以elide 动态分配 ??

编译器如何决定promise type
如果有这样的coro func task<float> foo(std::string x, bool flag); ,则生成的promise是: typename coroutine_traits<task<float>, std::string, bool>::promise_type;

如果coro func 是类成员方法,则class type会作为第二个模板参数传给coroutine_traits<>

coroutine_traits默认实现会在 return-type 中找一个嵌套的promise_type,如:

  1. namespace std::experimental
  2. {
  3. template<typename RET, typename... ARGS>
  4. struct coroutine_traits<RET, ARGS...>
  5. {
  6. using promise_type = typename RET::promise_type;
  7. };
  8. }
  1. template<typename T>
  2. struct task
  3. {
  4. struct task_promise { ... };
  5. using promise_type = task_promise<T>;
  6. ...
  7. };

用coroutine_handle引用指定一个activation frame
从 from_promise 中可以获得指向 coro frame 的handle

coroutine_handle不是一个RAII对象,要销毁得手工调用destroy(), 否则要维护计数增加开销; 我们应尽可能使用高层支持RAII的结构(比如cppcoro里有实现)

定制co_await
由Lewis Baker co_await文章可知,如果expr对应的类型的promise type有await_transform方法,则co_await 就会被解析成: co_await promise.await_transform(<expr>) ,好处有三:

  • 可以将不能awaitable的类型进行转化成awaitable
  • 禁止不可以await 的coro type
  • 有利于对normally awaitable type定制一些行为

定制co_yield
编译器将 co_yield <expr> 转化成 co_await promise.yield_value(<expr>) ,因为promise type就可以通过定义一个或多个 yield_value 来定制 co_yield行为

naked coroutine, Gor, cppcon17

https://www.youtube.com/watch?v=UL3TtTgt3oU

Understanding Symmetric Transfer, Lewis Baker, 2020.5

https://lewissbaker.github.io/2020/05/11/understanding_symmetric_transfer


接下来是Gor Nishanov cppcon n 步曲

Nano-coroutines, Gor Nishanov, CppCon 2018

nano指的是coroutines在纳秒级间切换
coroutine两种常见的使用pattern, 一种是generator, lazily-produced sequence, 另一种是async task
image.png

协程设计原则

  • 可扩展:billions of current coro
  • 高效: resume, suspend操作的开销和函数调用差不多
  • 与已有工具、代码无缝集成
  • Open: c++标准不定义具体的含义,而是让库开发者提供高层语义
  • Usable: 比如在异常不支持的环境下也能使用(比如google codepath, Windows kernel)

他曾经的一个例子,https://godbolt.org/g/26viuZ , 显示了编译器将这么一堆coro代码优化成几条汇编语句(我尝试了他的例子,但还不知如何用objdump得到网页编译器优化的结果);
他将传统的基于future回调与基于coroutine的网络程序进行了对比,认为下面这种写法更易读,且同样的高效,

  1. // 如果网络程序这样写,会不会好很多? (实际上 asio已经可以这样了)
  2. task<void> session(tcp::socket s, size_t block_size) {
  3. s.set_option(tcp::no_delay(true));
  4. std::vector<char> buf(block_size);
  5. for(;;) {
  6. size_t n = co_await async_read_some(s, buffer(buf.data()), block_size);
  7. n = co_await async_write(s, buffer(buf.data(), n));
  8. }
  9. }
  10. task<void> server(io_context& io, const tcp::endpoint ep, size_t size) {
  11. tcp::acceptor acceptor(io, ep);
  12. acceptor.listen();
  13. for (;;) {
  14. spawn(io, session(co_await async_accept(acceptor), size));
  15. }
  16. }

coroutines on database

令人意外的是,作者引用了学术界对coroutine在database上的研究,
Interleaving with Coroutines: A Practical Approach for Robust Index Joins
Exploiting Coroutines to Attack the “Killer Nanoseconds”

拿database 二分查找举例,当对内存随机查找时,一次内存操作大概60ns(在作者laptop上),而这期间,CPU只干了少量活,大部分时间在等待内存,称为memory stall (这么小的时间根本不适合切换到其他线程!). 于是想到,如果我们能利用CPU prefetch指令,让前一个lookup操作在等待内存时,启动第二个lookup处理数据,第二个memory stall时,启动第三个,终有一时刻,第一次内存数据已经到达了CPU,这样就切回第一次lookup中。这样在60ns的周期内,CPU被充分利用! (这其实是 do hyper-threading in software)如下图所示:
image.png

由作者改写的二分查找 (思想是 instruction stream interleaving),利用CPU预取指令,确实提高了性能,但代码变多且不好理解。解决办法是用协程 !

协程之二分查找

由c++ coroutine TS改写的二分查找是这样,

  1. // Gor Nishanov cppcon 2018 example
  2. template <typename Iterator, typename Value, typename Found, typename NotFound>
  3. auto binary_search(Iterator first, Iterator last, Value val, Found on_found, NotFound on_not_found) -> task<void> {
  4. auto len = last - first;
  5. while (len > 0) {
  6. auto half = len / 2;
  7. auto middle = first + half;
  8. auto middle_key = co_await prefetch(*middle); // if memory access is slow, suspend it
  9. if (middle_key < val) {
  10. first = middle + 1;
  11. len = len - half - 1;
  12. } else {
  13. len = half;
  14. }
  15. if (middle_key == val) {
  16. co_return on_found(val, middle);
  17. }
  18. }
  19. co_return on_not_found(val);
  20. }

启动多个二分查找的orchestrator

  1. void Multilookup(const std::vector<int>& v, const vector<int>& lookups, int concurrency) {
  2. size_t found_count = 0;
  3. size_t not_fount_count = 0;
  4. throtter t(concurrency);
  5. for (auto k: lookups) {
  6. t.spawn(binary_search(v.begin(), v.end(), k,
  7. [&](auto) { ++found_count; },
  8. [&](auto) { ++not_fount_count; }));
  9. }
  10. t.join();
  11. }

注意,这里的模型就是fork-join,派生出一大堆“协程”,在最后等待它们

性能对比

用perf-stat 获得profiling

image.png

为什么coroutine 版本比hand-crafted版本好

作者也是猜测,相同的数组,相同的lookup ,为什么Coroutine 版本要好?
简而言之,就是coroutine 版本更有利于compiler 优化 ??

利用了协程切换时间的优势:

coro 切换时间 < 1ns
fibers, stackful coro 切换时间 10-50ns
线程切换 1us

coroutine TS目前的状态

vs 2015+, clang 5.1+已经实现了,gcc实现在进行中

问题中有人问道:如果在coro里加上断点调试,会怎么样?这个问题值得探究一下

作者顺便提到了这个:Impact of coroutines on current and upcoming library facilities

详细源码在这

https://github.com/GorNishanov/await/tree/master/2018_CppCon

QA

有人问:
由于程度跑在不同配置、架构的机器上,如何避免手工调试throtter ?
目前只能手工调

调试起来会不会很麻烦, nightmare ?
没什么特别需注意的 ?

16,20 的参数是凭经验试出来的,不是故意让 hand-crafted 实现性能更差

有观众:你不是优化某一次的search,你是让所有search在更小的时间内完成

Gor 在youtube 评论中:
coro 可以用imperative control flow 去实现状态机,但不是所有状态机都适合用 coro 来做;
我也觉得底层接口不好用,标准能提供实现好的东西供普通c++用户使用就最好了

有人提到,即使不用 prefetch,coro 版本和hand-crafted 版本也比naive 版本快。 为何??


await 2.0: Stackless Resumable Functions,CppCon 2014, Gor Nishanov

(这个视频在channel9上,有字幕无广告,youtube上的貌似没有字幕)

Knuth在1968年定义coro是”generalization of subroutine”,除了有subroutine的call, return语句,还有suspend, resume方法;

协程分类:
symmetric: 如win32 fibers, boost::context
asymmetric: c#

stackful vs stackless:
举例谈到go是怎么实现stackful的,它是采用了chained stack

stackless coro并不是没有状态,其状态由编译器放在堆上,拿下面这个例子来说,
image.png

编译器在开始和结束时,允许库开发者定义initial_suspend, final_suspend; 每一个被await的expr都必须满足awaitable语义;

提问有人问题:库开发者是否可以覆盖用以生成coro frame的allocator ?是可以的,它甚至允许直接使用caller的stack

Example中谈到了recursive_generator<>,可以用来递归遍历tree等结构;

库开发者既可以设计新的coro types,如generator, goroutine, spawnable, task,也可以在已有的东西进行改造,如future, concurrency::task, IAsyncAction,IAsyncOperation

awaitable

image.png

trivial awaitable: suspend_always{}, suspend_never{},它们是用用的;
simple awaitable #1

  1. // Gor cppcon 2014 example
  2. struct lock_or_suspend {
  3. std::unique_lock<std::mutex> lock;
  4. lock_or_suspend(std::mutex& mut) : lock(mut, std::try_to_lock) {}
  5. bool await_read() { return lock.owns_lock(); }
  6. template <typename Func>
  7. void await_suspend(Func cb) {
  8. std::thread t([this, cb] {
  9. lock.lock();
  10. cb();
  11. });
  12. t.detach();
  13. }
  14. auto await_resume() { return std::move(lock); }
  15. };

simple awaiter #2: adapt boost future to deal with await

与c api交互

Gor在这里把coroutine_handle<>写成了resumable_handle<>,后者是标准中的老的叫法

这一keynote,感觉作者讲得不成体系。


Coroutines: what they can’t do, CppCon 2017, Toby Allsopp

图画得好
image.png

可以在另外一个线程中被resume, destroy
image.png

他举了simple coroutine,

  1. lazy<int> calculate() {
  2. int result = hard_work();
  3. co_return result;
  4. }

编译器为calculate生成的代码 (他说TS中就是这么举例的),这与James McNellis cppcon2016 讲得不一样

  1. using promise_type = coroutine_traits<int>::promise_type;
  2. {
  3. promise_type p; // promise实际上是存储在coro state中,这样写成局部变量不对!
  4. auto r = p.get_return_object();
  5. co_await p.initial_suspend();
  6. try {
  7. int result = hard_worker();
  8. p.return_value(result);
  9. goto final_suspend;
  10. } catch (...) {
  11. p.unhandled_exception();
  12. }
  13. final_suspend:
  14. co_await p.final_suspend();
  15. destroy:
  16. //delete
  17. }

协程状态
image.png

他分别讲到了co_await, co_yield, for co_await 的编译器生成代码


Intro to C++ coroutines, CppCon 2016, James McNellis

作者举了一个tcp_reader的例子,先是用异步方式来写,就写成了类似seastar风格的代码,可读性确实不好;他比喻这种写法就好像写一个较复杂的正则表达式,你可能会写,但你却不能百分百确定写对了;

从函数的签名上是看不出它是不是coroutine的,是不是得看实现,这也意味着换了函数实现对用户是无感知的;

有两种特殊的awaitable, suspend_always{} 的await_ready()始终返回为false, suspend_never{} 反之;

一般来讲,coroutine frame必须是动态分配的,当coro被suspend时,它就失去对stack的使用权了;operator new可以为coro重载; 且编译器在适当的时候(如果它确定coro的栈不会超出caller栈的大小)可以优化动态分配,直接使用caller的stack;且coro的栈创建肯定是在coro运行之前发生的;编译器还会把Coro frame的句柄handle传给caller

coroutine_handle的接口

image.png

其中,operator()和resume干相同的事,允许caller resume coro;
from_address, to_address是为了和capi交互,这样可以通过void* 互转;

coroutine_handle继承自coroutine_handle<>,增加了promise(), from_promise()方法,因为promise是编译器分配在frame里的

例子

  1. resumable_thing counter() {
  2. cout << "counter called\n";
  3. for (int i = 1; ; i++) {
  4. co_await suspend_always{};
  5. cout << "counter: resumed(#" << i << ")\n";
  6. }
  7. }

首先编译器先生成这样的frame结构:
image.png

然后编译器会注入一些代码。在开始前和结束后允许上层决定是否要suspend
image.png

co_return

编译器会给如coreturn 30这样的语句,生成下面这种代码,(也就意味着promise要提供return_value方法)(_get_value最后不用写return resumable_thing ??)
image.png

要注意,如果想在main中获取到coro包含的value,需要让final_suspend为suspend_always,这样_context才不会在获取值之前被销毁;


stackless coroutines with VS2015, 2015

stackful协程是有自己的栈,而stackless协程需要编译器为其在堆上创建activation frame;
在这篇文章中,作者介绍了基于fiber的stackful协程,但其问题在于fiber开销大,默认栈大小 1MB,显然无法启动很多协程;

而在新提案N4286里,集中谈stackless coroutine

awaitable types

For example, in the sample code above, when we call: the type on which we want to await is a PPL task. So, with our await statement we are asking the compiler to generate code that suspends on a task, and resumes after the task is completed. The await compiles because the new library provides these three functions for PPL tasks:

__await delay(2000);
bool await_ready(task& t) ``const {
``return t.is_done();
}
void await_suspend(task& t, resumable_handle rh) {
``t.then([rh](task&){ rh(); };
}
void await_resume(task& t) {
``t.get();
}

它就是一种能支持await语句的类型,在这里就是delay()返回的PPL task;
当编译器碰到await expr时,就会生成以下三个函数,其参数就会接awaitable 对象

  1. // Returns true is the results of the asynchronous operation is already available.
  2. bool await_ready(T& t) const
  3. // Suspends the execution until the asynchronous operation completes.
  4. void await_suspend(T& t, resumable_handle<> rh)
  5. // Resumes the execution from where it had suspended.
  6. void await_resume(T& t)

Using C++ Resumable Functions with Libuv

https://devblogs.microsoft.com/cppblog/using-ibuv-with-c-resumable-functions/

C++ coroutine TS example on linux

https://wandbox.org/permlink/Dth1IO5q8Oe31ew2
依赖:llvm, clang
ubuntu/debian下应该需要安装libc++-dev, libc++abi-dev

mac下的coroutine库在/Library//Developer/CommandLineTools/usr/include/c++/v1/experimental/coroutine

编译命令:

clang++ -Wall -Wextra -std=gnu++2a -fcoroutines-ts -stdlib=libc++ coro.cc


building coroutine, mtu.edu

很形象的讲解,谈到了为何要单独给coroutine分出栈桢

google提出的关于coroutine TS的一些issue, 2018

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0973r0.pdf

coroutine可以对错误处理更加方便;

TS的动态分配问题

在expected-base的错误处理方面,coro分配了heap 内存保存协程状态,但在这种情况下是不需要的,因为它不会在suspension之后被恢复;对此,TS 作者解释说:当分配不需要的时候可以被优化掉。但作者对此保持怀疑:

  1. 没有证据显示编译器可以很可靠地做到这一点
  2. 哪怕可以可靠做到,编程者可能不信任(就像copy elision一样,许多编程者不会选择在函数内返回big object by value,尽管编译器说可以优化掉)
  3. 这种动态分配设计与C++ 哲学相悖,c++相比 于其它语言一个重要地点在于,提供强大抽象的同时,允许编程者根据情况控制性能,而分配却妥协了这种语言优势,使得编程者无法对代码的性能建立可靠的mental model

另外,TS未能给编程者对分配给予足够的控制,仅仅重载new显得很不足;

作者的一个类比:对TS分配问题,它就好像是我们把vector作为array的底层实现,然后告诉编程者当大小固定时,可以避免动态分配;我们很显然不会满意于这种说法

const ref参数,危险

  1. future<string> ConCat(const string& prefix, future<string> suffix> {
  2. co_return (prefix + co_await suffix);
  3. }

如果我们传右值给prefix,那么有可能待这个coro func resume时,prefix访问已非法

放弃使用return对用户不太友好,使迁移变得困难

希望标准委员会解决以上的issues


C++ coroutine TS example on VS2017

编译时要加/await选项
参考:
https://paoloseverini.wordpress.com/2015/03/06/stackless-coroutines-with-vs2015/
https://heejune.me/2017/02/20/beginning-the-coroutine-with-visual-studio-2015-update-3-part-1/

Structured concurrency, writing concurrent code with coroutines, Lewis Baker, cppcon2019

他说把并发看成 resource,我觉得更像是 means (手段)

Other References

知乎网友的一篇协程介绍: c++20协程入门
标准中协程提案论文