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

相关推荐
hggngx548h11 天前
有哪些C++20特性可以在Dev-C++中使用?
开发语言·c++·c++20
R&L_2018100114 天前
C++20之三路比较运算符
c++20·c++ 新特性
buvsvdp50059ac15 天前
如何在Visual Studio中启用C++17或C++20?
c++·c++20·visual studio
TiAmo zhang16 天前
现代C++的AI革命:C++20/C++23核心特性解析与实战应用
c++·人工智能·c++20
m0_7482480217 天前
C++20 协程:在 AI 推理引擎中的深度应用
java·c++·人工智能·c++20
落羽的落羽18 天前
【C++】现代C++的新特性constexpr,及其在C++14、C++17、C++20中的进化
linux·c++·人工智能·学习·机器学习·c++20·c++40周年
kyle~22 天前
CPU调度---协程
java·linux·服务器·数据库·c++20
charlie1145141912 个月前
精读C++20设计模式:行为型设计模式:中介者模式
c++·学习·设计模式·c++20·中介者模式
charlie1145141912 个月前
理解C++20的革命特性——协程引用之——利用协程做一个迷你的Echo Server
网络·学习·socket·c++20·协程·epoll·raii
charlie1145141912 个月前
理解C++20的革命特性——协程支持2:编写简单的协程调度器
c++·学习·算法·设计模式·c++20·协程·调度器