C++ coroutine 简单的例子

本文介绍了C++20中协程(coroutine)的使用,特别是Awaitable接口的实现。内容包括:1) `is_ready` 函数,用于检查协程是否已完成;2) `await_suspend` 函数,接收编译器生成的协程句柄以挂起和恢复执行;3) `await_resume` 函数,定义协程恢复时的返回值。通过理解这些概念,读者能够更好地掌握C++20协程的运用。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <thread>
#include <coroutine>
#include <chrono>
#include <functional>

// g++-10 -std=c++2a coroutineDemo.cpp -fcoroutines -lpthread

using call_back = std::function<void(int)>;
void Add100ByCallback(int init, call_back f) // 异步调用
{
	std::thread t([init, f]() {
		std::this_thread::sleep_for(std::chrono::seconds(5));
		f(init + 100);
		});
	t.detach();
}

struct Add100AWaitable
{
	Add100AWaitable(int init) :init_(init) {}
	bool await_ready() const { return false; }
	int await_resume() { return result_; }
	void await_suspend(std::coroutine_handle<> handle)
	{
		auto f = [handle, this](int value) mutable {
			result_ = value;
			handle.resume();
		};
		Add100ByCallback(init_, f); // 调用原来的异步调用
	}
	int init_;
	int result_;
};

struct Task
{
	struct promise_type {
		auto get_return_object() { return Task{}; }
		auto initial_suspend() { return std::suspend
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值