C#:抽象类和接口
2026/9/28 20:46:44
C++20引入的协程(Coroutines)是C++异步编程的革命性特性,也是大厂面试的高频考点。协程让异步代码写起来像同步代码一样简洁,彻底解决了回调地狱问题。本文将从零开始,带你理解协程的核心概念,并通过实战代码掌握协程的应用。
协程是一种可以暂停执行并在稍后恢复执行的函数。与普通函数不同,协程可以多次返回。
| 特性 | 普通函数 | 协程 |
|---|---|---|
| 执行方式 | 一次性执行完毕 | 可暂停、可恢复 |
| 返回次数 | 一次 | 多次 |
| 状态保持 | 不保持 | 保持局部变量 |
| 适用场景 | 同步计算 | 异步IO、生成器 |
| 关键字 | 作用 | 使用场景 |
|---|---|---|
co_await | 暂停协程,等待异步操作完成 | 异步IO |
co_return | 返回值并结束协程 | 返回结果 |
co_yield | 产出一个值并暂停 | 生成器 |
协程 = 协程帧(Coroutine Frame) + 承诺(Promise) + awaiter| 组件 | 功能 |
|---|---|
| Promise | 协程与调用者之间的桥梁 |
| Coroutine Frame | 保存协程状态(局部变量、暂停点) |
| Awaiter | 定义co_await的行为 |
#include<coroutine>#include<iostream>#include<optional>// 承诺类型:定义协程的行为template<typenameT>structGenerator{structpromise_type;usinghandle_type=std::coroutine_handle<promise_type>;handle_type handle_;Generator(handle_type h):handle_(h){}~Generator(){if(handle_)handle_.destroy();}// 移动语义Generator(Generator&&other)noexcept:handle_(other.handle_){other.handle_=nullptr;}// 获取下一个值std::optional<T>next(){handle_.resume();if(handle_.done()){returnstd::nullopt;}returnhandle_.promise().value;}structpromise_type{std::optional<T>value;Generatorget_return_object(){returnGenerator{handle_type::from_promise(*this)};}std::suspend_alwaysinitial_suspend(){return{};}std::suspend_alwaysfinal_suspend()noexcept{return{};}std::suspend_alwaysyield_value(T val){value=val;return{};}voidreturn_void(){}voidunhandled_exception(){std::terminate();}};};// 使用协程生成斐波那契数列Generator<int>fibonacci(){inta=0,b=1;while(true){co_yiel