
要使用C++20的协程(coroutines),你需要了解三个核心概念:可暂停的函数(即协程)、promise type 和 awaiter。C++20协程不是像Go或Python那样“开箱即用”的轻量级线程,而是提供底层机制,需要你配合自定义类型来实现具体行为。
一个函数是协程,只要它内部使用了以下关键字之一:
编译器会把包含这些关键字的函数转换为状态机。
下面是一个使用 co_yield 实现的简单整数生成器:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <coroutine>
#include <exception>
struct Generator {
struct promise_type {
int current_value;
Generator get_return_object() {
return Generator(std::coroutine_handle<promise_type>::from_promise(*this));
}
std::suspend_always initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_void() {}
std::suspend_always yield_value(int value) {
current_value = value;
return {};
}
void unhandled_exception() {
std::terminate();
}
};
using handle_type = std::coroutine_handle<promise_type>;
handle_type h_;
explicit Generator(handle_type h) : h_(h) {}
~Generator() { if (h_) h_.destroy(); }
// 移动构造
Generator(Generator&& other) noexcept : h_(other.h_) {
other.h_ = nullptr;
}
Generator& operator=(Generator&& other) noexcept {
if (this != &other) {
if (h_) h_.destroy();
h_ = other.h_;
other.h_ = nullptr;
}
return *this;
}
// 删除拷贝
Generator(const Generator&) = delete;
Generator& operator=(const Generator&) = delete;
int value() const { return h_.promise().current_value; }
bool move_next() {
if (!h_ || h_.done()) return false;
h_.resume();
return !h_.done();
}
};
Generator int_sequence(int start = 0, int step = 1) {
auto value = start;
while (true) {
co_yield value;
value += step;
}
}
int main() {
auto gen = int_sequence(10, 5);
for (int i = 0; i < 5; ++i) {
if (gen.move_next()) {
std::cout << "Value: " << gen.value() << '\n';
}
}
return 0;
}
输出:
Value: 10 Value: 15 Value: 20 Value: 25 Value: 30
promise_type 是协程逻辑的核心,它控制协程的生命周期和行为:
确保你的编译器支持C++20协outines:
例如 g++ 编译命令:
g++ -std=c++20 -fcoroutines -o coroutine_example coroutine_example.cpp
你可以定义自己的 awaiter 类型来配合 co_await:
struct simple_awaiter {
bool await_ready() { return false; } // 返回 true 则不挂起
void await_suspend(std::coroutine_handle<> h) {
// 可以安排其他任务,然后手动恢复 h()
h.resume(); // 立即恢复 —— 实际中可能延迟
}
int await_resume() { return 42; }
};
Generator example_with_await() {
auto val = co_await simple_awaiter{};
co_return val;
}
co_await 会调用 await_ready、await_suspend、await_resume 来控制挂起与恢复流程。
基本上就这些。C++20协程灵活但复杂,适合构建异步框架、生成器、任务调度等高级抽象。初学建议从生成器模式入手,理解 promise 和 handle 的交互。以上就是c++++怎么使用C++20的coroutines协程_c++ C++20 coroutines使用方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号