c++20 协程本质
背景:
最近因项目关系,web端,js异步调用,发现跟本门的C++20 还是有些不一样的,本文主要从另外一个角度来看
什么是协程
协程是能暂停执行以在之后恢复的函数。协程是无栈的:它们通过返回到调用方暂停执行,并且恢复执行所需的数据与栈分离存储。这样就可以编写异步执行的顺序代码(例如不使用显式的回调来处理非阻塞输入/输出),还支持作用于惰性计算的无限序列上的算法及其他用途。
腾讯用c语言实现了一个有栈携程,libco,有兴趣的同学可以看下,跟本文讲的协程不太一样。
当一个函数中出现 co_yeild, co_wait, co_return,它就是一个协程
了解一些概念
承诺(promise)对象,从协程内部操纵。协程通过此对象提交其结果或异常。
协程句柄 (coroutine handle),从协程外部操纵。这是用于恢复协程执行或销毁协程帧的非拥有柄
co_yeild, co_wait, co_return ,可以参照https://zh.cppreference.com/w/cpp/language/coroutines里边自行看下,
我们主要分析协程在编译后会变成什么样子
示例代码
C++ #include <coroutine> #include <exception> #include <iostream> #include <thread>
struct Generator {
class ExhaustedException : std::exception {};
struct promise_type {
int value; bool is_ready = false;
std::suspend_always initial_suspend() { return {}; };
std::suspend_always final_suspend() noexcept { return {}; }
std::suspend_always yield_value(int value) {
this->value = value; is_ready = true; return {}; }
void unhandled_exception() {
}
Generator get_return_object() {
return Generator{std::coroutine_handle<promise_type>::from_promise(*this)}; }
void return_void() {} };
std::coroutine_handle<promise_type> han |