这一节分析协程状态结构,指的是 官方文档中的 coroutine state
the coroutine state, which is internal, dynamically-allocated storage (unless the allocation is optimized out), object that contains
- the promise object
- the parameters (all copied by value)
- some representation of the current suspension point, so that a resume knows where to continue, and a destroy knows what local variables were in scope
- local variables and temporaries whose lifetime spans the current suspension point.
姑且命名此结构为CoroState
先将分析结果贴出来,此结构布局只针对样例。
另一方面,因为coroutine
与coroutine函数各自独立,所以可以猜测CoroState
中与临时或本地变量有关的东西应该是指针或者状态式的。
CoroState 结构布局
type | range | naming | meaning |
---|---|---|---|
void * | 0-8 | entry_ | resume entry |
void * | 8-16 | entry2_ | not seen yet |
void * | 16-24 | promise_ | promise itself(no pointer) |
void * | 24-32 | act_coro_ | actived coro in its frame ? |
int16_t | 32-34 | stat_ | coro state see [coro state](#coro 状态) |
bool | 34-35 | ifvalid_ | flag indicates if coro frame is valid |
coro 状态
这里有一个很重要的状态成员 stat_
,先将状态含义贴出来,以便于阅读后边的代码
val | mean |
---|---|
0 | after call promise::get_return_object |
2 | after call promise::initial_suspend |
汇编分析
结论(cc)
CoroFunc
本身被gcc编译成空壳函数体,其内部的语句都编译在CoroFunc.Frame
,即另一个代码区。其本身只负责初始化Coro帧
并调用promise::initial_suspend
、promise::get_return_object
与coroutine::resume
. 伪码如下1
2
3
4
5
6
7
8
9
10FORCE_NOINLINE coroutine CAwait1(){
CoroState * frame = new CoroState;
frame->ifValid_ =true;
frame->entry_ = 0xaaa;// resume entry
frame->entry2_ = 0xbbb;// another resume point
auto pro =frame->promise_;
pro->promise();// 初始化promise
coroutine ret = pro->get_return_object(); // 拿到返回对象
co_await pro->initial_suspend();
}
compile config
1 | cmake_minimum_required(VERSION 3.10) |
utils.hpp
1 |
|