C++20 协程入门
co_await/co_yield/co_return、生成器模式、异步任务
C++20 协程入门
协程让函数可以暂停和恢复——不用回调,不用状态机。异步、生成器都用它。
学完本章你将: 掌握 co_await/co_yield/co_return、生成器模式。
生成器
cpp
#include <coroutine>
#include <iostream>
// 简易生成器类型
template <typename T>
struct Generator {
struct promise_type {
T current;
auto get_return_object() { return Generator{this}; }
auto initial_suspend() { return std::suspend_always{}; }
auto final_suspend() noexcept { return std::suspend_always{}; }
auto yield_value(T value) { current = value; return std::suspend_always{}; }
void return_void() { }
void unhandled_exception() { std::terminate(); }
};
// 迭代器支持(简化)
bool move_next() { return coro && (coro.resume(), !coro.done()); }
T current() { return coro.promise().current; }
~Generator() { if (coro) coro.destroy(); }
private:
std::coroutine_handle<promise_type> coro;
explicit Generator(promise_type* p)
: coro(std::coroutine_handle<promise_type>::from_promise(*p)) { }
};
// 使用 co_yield
Generator<int> fibonacci() {
int a = 0, b = 1;
while (true) {
co_yield a;
auto next = a + b;
a = b; b = next;
}
}
int main() {
auto gen = fibonacci();
for (int i = 0; i < 10; i++) {
gen.move_next();
std::cout << gen.current() << " "; // 0 1 1 2 3 5 8 13 21 34
}
}
三个关键字
cpp
co_await expr; // 暂停并等待
co_yield value; // 产生一个值并暂停
co_return; // 返回并结束