C++20协程——最简单的协程

一个函数返回了"协程接口",那么这个函数就是一个协程。

协程接口要求必须有promise_type。(awaitable是另外的,非必须。)

协程句柄(代表协程)是编译器负责创建的,我们只管用就行了。

最小化示例如下:

cpp 复制代码
#include <coroutine>

#include <iostream>

struct CoroutineInterface {
	struct promise_type {
		CoroutineInterface get_return_object() {
			return CoroutineInterface(std::coroutine_handle<promise_type>::from_promise(*this));
		}
		auto initial_suspend() {
			return std::suspend_always();
		}

		auto final_suspend()noexcept {
			return std::suspend_always();
		}
		void return_void() noexcept {

		}
		void unhandled_exception() {
			std::terminate();
		}
	};

	CoroutineInterface(std::coroutine_handle<promise_type> co_handle) {
		co_handle_ = co_handle;
	}

	std::coroutine_handle<promise_type> co_handle_;
};

CoroutineInterface GetNumbers() {
	// co_wait initial_suspend();
	for (int i = 0; i < 8; ++i) {
		std::cerr << i << "\n";
		co_await std::suspend_always();
	}
	// co_wait final_suspend();
	co_return;
}
int main(void) {

	CoroutineInterface co_interface = GetNumbers();
	while (!co_interface.co_handle_.done()) {
		std::cerr << "resume:";
		co_interface.co_handle_.resume();
	}
	std::cerr << "successfully end\n";
	return 0;
}

函数(协程)执行时,编译器会在代码块最前面执行cowait initial_suspend(),并且在函数co_return之前(或者在异常跳出之前)执行cowait final_suspend()

initial_suspend()final_suspend()是标准库提供的两个awaitable(可等待体)。

initial_suspend()final_suspend()分别用于控制协程开始、协程即将结束时是否要挂起(挂起后会转移执行权,可以转移给调用者,或者其他协程)。

相关推荐
普通网友17 小时前
记录我适配iOS26遇到的一些问题
c++20
前进吧-程序员1 天前
C++20/23 Ranges:从「迭代器对」到「可组合管道」
c++20
Shan12056 天前
实例分析:C++20的std::jthread
c++20
charlie1145141916 天前
基于开源项目的现代C++工程实践——OnceCallback 前置知识(下):C++20/23 高级特性
c++·开源·c++20
Hical_W6 天前
Hical 踩坑实录五部曲(二):MSVC / GCC / Clang 三平台 C++20 编译差异
linux·windows·经验分享·嵌入式硬件·macos·开源·c++20
Shan12058 天前
C++20中带有约束条件的new
c++20
Hical_W11 天前
用 Hical + MySQL 5 分钟搭建 CRUD API(C++20 协程版)
数据库·mysql·c++20
Hical_W11 天前
从 io_context 出发,掌握 C++20 协程式异步 I/O,学会 TCP 服务器、定时器和多线程模型,结合 Hical 框架实战解读
服务器·tcp/ip·开源·c++20
c++之路15 天前
C++20概述
java·开发语言·c++20
故事还在继续吗16 天前
C++20关键特性
开发语言·c++·c++20