C++20 协程 Promise 类型与自定义 Awaitable 对象
深入协程框架的核心——promise_type 与 awaitable 接口。实现一个能延迟执行的协程,展示如何手动编写 promise 类型并挂起/恢复执行。 · 难度:入门 · +10XP
C++20 协程 Promise 类型与自定义 Awaitable 对象
协程通过 promise_type 控制行为,包括初始挂起、返回值、异常处理等。自定义 awaitable 需要实现 await_ready、await_suspend、await_resume。本教程构建一个简易的 DelayAwaiter,使协程能够暂停固定时间后再恢复。
#include <coroutine>
#include <thread>
#include <chrono>
struct DelayAwaiter {
std::chrono::milliseconds dur;
bool await_ready() const { return dur.count() == 0; }
void await_suspend(std::coroutine_handle<> h) {
std::thread([h, this](){
std::this_thread::sleep_for(dur);
h.resume();
}).detach();
}
void await_resume() {}
};