实现协程生成器
面试考点
协程生成器(Generator)是 C++20 协程最常见的应用。面试官考察你是否理解 promise_type 的生命周期、co_yield 的挂起/恢复机制、coroutine_handle 的管理,以及如何实现一个支持范围 for 循环的惰性序列生成器。
核心概念
Generator 是一个惰性求值的序列:每次调用 next() 或迭代时,协程恢复执行到下一个 co_yield,产出一个值后再次挂起。Generator 不会一次性计算所有值,而是按需产出,适合无限序列和大数据流。核心是 promise_type 定义了协程的行为:initial_suspend 决定是否懒启动,yield_value 存储产出的值并挂起,final_suspend 决定结束时是否保持协程帧。
基本示例
#include <iostream>
#include <coroutine>
#include <optional>
#include <utility>
#include <stdexcept>
#include <vector>
#include <string>
#include <cstdint>
// ============================
// Generator 模板类
// ============================
template<typename T>
class Generator {
public:
// promise_type:定义协程的行为
struct promise_type {
std::optional<T> current_value; // 当前产出的值
// 协程创建时返回 Generator 对象
Generator get_return_object() {
return Generator{
std::coroutine_handle<promise_type>::from_promise(*this)
};
}
// 初始挂起:suspend_always 表示懒启动
// 协程创建后不立即执行,等第一次 next() 调用时才开始
std::suspend_always initial_suspend() noexcept { return {}; }
// 最终挂起:suspend_always 表示协程结束时保持帧
// 这样 Generator 析构时才能安全地 destroy 协程帧
std::suspend_always final_suspend() noexcept { return {}; }
// co_yield value 的处理
// 存储值并挂起协程,把控制权还给调用者
std::suspend_always yield_value(T value) {
current_value = std::move(value);
return {};
}
// 不支持 co_return 带值(Generator 只用 co_yield)
void return_void() {}
// 异常处理
void unhandled_exception() {
throw; // 重新抛出,让调用者处理
}
};
// 协程句柄类型
using handle_type = std::coroutine_handle<promise_type>;
// 构造函数:接收协程句柄
explicit Generator(handle_type h) : handle_(h) {}
// 禁止拷贝(协程句柄是唯一的)
Generator(const Generator&) = delete;
Generator& operator=(const Generator&) = delete;
// 允许移动
Generator(Generator&& other) noexcept : handle_(other.handle_) {
other.handle_ = nullptr;
}
Generator& operator=(Generator&& other) noexcept {
if (this != &other) {
if (handle_) handle_.destroy();
handle_ = other.handle_;
other.handle_ = nullptr;
}
return *this;
}
// 析构:销毁协程帧
~Generator() {
if (handle_) handle_.destroy();
}
// 获取下一个值
bool next() {
if (handle_ && !handle_.done()) {
handle_.resume(); // 恢复协程执行到下一个 co_yield
return !handle_.done(); // 检查协程是否结束
}
return false;
}
// 获取当前值
const T& value() const {
return *handle_.promise().current_value;
}
// ============================
// 迭代器支持(支持范围 for)
// ============================
struct sentinel {}; // 哨兵类型,表示序列结束
struct iterator {
handle_type handle;
// 前置 ++:恢复协程到下一个 co_yield
iterator& operator++() {
handle.resume();
return *this;
}
// 解引用:获取当前值
const T& operator*() const {
return *handle.promise().current_value;
}
// 与哨兵比较:检查协程是否结束
bool operator==(sentinel) const {
return handle.done();
}
bool operator!=(sentinel s) const {
return !(*this == s);
}
};
// begin():恢复协程到第一个 co_yield
iterator begin() {
if (handle_) {
handle_.resume(); // 执行到第一个 co_yield
}
return iterator{handle_};
}
// end():返回哨兵
sentinel end() { return {}; }
private:
handle_type handle_;
};
// ============================
// 生成器函数示例
// ============================
// 斐波那契数列生成器(无限序列)
Generator<uint64_t> fibonacci() {
uint64_t a = 0, b = 1;
while (true) {
co_yield a;
uint64_t temp = a;
a = b;
b = temp + b;
}
}
// 范围生成器
Generator<int> range(int start, int end, int step = 1) {
for (int i = start; i < end; i += step) {
co_yield i;
}
}
// 从容器中逐个产出
template<typename Container>
Generator<typename Container::value_type> from_container(Container c) {
for (auto& item : c) {
co_yield item;
}
}
// 过滤生成器:只产出满足条件的值
template<typename T, typename Pred>
Generator<T> filter(Generator<T> gen, Pred pred) {
while (gen.next()) {
if (pred(gen.value())) {
co_yield gen.value();
}
}
}
// 映射生成器:对每个值应用变换
template<typename T, typename Func>
Generator<std::invoke_result_t<Func, const T&>>
transform(Generator<T> gen, Func func) {
while (gen.next()) {
co_yield func(gen.value());
}
}
// 取前 N 个值
template<typename T>
Generator<T> take(Generator<T> gen, size_t n) {
size_t count = 0;
while (count < n && gen.next()) {
co_yield gen.value();
count++;
}
}
// ============================
// 测试
// ============================
void test_fibonacci() {
std::cout << "--- 斐波那契 ---" << std::endl;
auto fib = fibonacci();
for (int i = 0; i < 15 && fib.next(); i++) {
std::cout << fib.value() << " ";
}
std::cout << std::endl;
}
void test_range() {
std::cout << "\n--- range(0, 10, 2) ---" << std::endl;
// 使用范围 for 循环
for (auto v : range(0, 10, 2)) {
std::cout << v << " ";
}
std::cout << std::endl;
}
void test_container() {
std::cout << "\n--- 容器生成器 ---" << std::endl;
std::vector<std::string> names = {"Alice", "Bob", "Charlie"};
for (const auto& name : from_container(names)) {
std::cout << name << " ";
}
std::cout << std::endl;
}
void test_composition() {
std::cout << "\n--- 组合:取前10个斐波那契中的偶数 ---" << std::endl;
auto gen = take(
filter(fibonacci(), [](uint64_t n) { return n % 2 == 0; }),
10
);
while (gen.next()) {
std::cout << gen.value() << " ";
}
std::cout << std::endl;
}
int main() {
test_fibonacci();
test_range();
test_container();
test_composition();
return 0;
}Generator 的协程工作流
| 阶段 | 调用 | 说明 |
|---|---|---|
| 创建 | generator_func() | 编译器分配协程帧,调用 get_return_object |
| 初始挂起 | initial_suspend() | suspend_always → 懒启动,不立即执行 |
| 第一次恢复 | handle.resume() / begin() | 执行协程体直到第一个 co_yield |
| 产出值 | co_yield value | 调用 yield_value,存储值,挂起 |
| 后续恢复 | handle.resume() / ++iterator | 从上次 co_yield 处继续执行 |
| 结束 | 协程函数返回 | 调用 return_void,然后 final_suspend |
| 销毁 | handle.destroy() / ~Generator | 释放协程帧 |
promise_type 关键函数
| 函数 | 返回类型 | 作用 |
|---|---|---|
| get_return_object() | Generator | 创建返回给调用者的对象 |
| initial_suspend() | suspend_always | 懒启动(suspend_never 则立即执行) |
| final_suspend() | suspend_always | 保持帧(suspend_never 则自动销毁) |
| yield_value(T) | suspend_always | 存储值并挂起 |
| return_void() | void | 协程正常结束 |
| unhandled_exception() | void | 处理协程中的异常 |
常见问题
为什么 initial_suspend 返回 suspend_always?
这实现了懒启动:协程创建后不立即执行,等第一次 resume() 调用时才开始。如果返回 suspend_never,协程创建后会立即执行到第一个 co_yield,这在某些场景下是合适的,但 Generator 的惯用做法是懒启动。
为什么 final_suspend 返回 suspend_always?
如果返回 suspend_never,协程结束时会自动销毁协程帧。但 Generator 的析构函数也会调用 handle_.destroy(),导致双重销毁。返回 suspend_always 让协程帧保持,由 Generator 的析构函数统一管理生命周期。
co_yield 和 co_return 能混用吗?
可以,但 Generator 通常只用 co_yield。co_return 表示协程结束。如果 promise_type 同时定义了 yield_value 和 return_value,两者可以共存。但 return_void 和 return_value 不能同时存在。
适用场景
- 惰性序列生成(斐波那契、素数、自然数)
- 大数据流的逐条处理
- 文件逐行读取
- 管道式数据处理(filter、map、take)
注意事项
- Generator 不可拷贝,只能移动(协程句柄是唯一的)
- 协程帧分配在堆上(编译器可能做 HALO 优化消除)
- 协程中抛出的异常会在 resume() 调用处重新抛出
- 无限生成器要确保调用者有终止条件
- final_suspend 返回 suspend_always 时必须在析构函数中 destroy
总结
协程生成器的核心是 promise_type 定义协程行为:initial_suspend 实现懒启动,yield_value 存储值并挂起,final_suspend 保持帧由 Generator 管理。co_yield 在每个产出点挂起协程,resume() 恢复执行到下一个 co_yield。面试中要能完整实现 Generator 模板类(包括 promise_type、迭代器支持),写一个斐波那契生成器函数,解释协程的挂起/恢复机制和生命周期管理。