#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
C++ coroutine 简单的例子
最新推荐文章于 2024-08-30 07:15:00 发布
本文介绍了C++20中协程(coroutine)的使用,特别是Awaitable接口的实现。内容包括:1) `is_ready` 函数,用于检查协程是否已完成;2) `await_suspend` 函数,接收编译器生成的协程句柄以挂起和恢复执行;3) `await_resume` 函数,定义协程恢复时的返回值。通过理解这些概念,读者能够更好地掌握C++20协程的运用。
摘要由CSDN通过智能技术生成