⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

C++20 协程 Promise 类型与自定义 Awaitable 对象

深入协程框架的核心——promise_type 与 awaitable 接口。实现一个能延迟执行的协程,展示如何手动编写 promise 类型并挂起/恢复执行。 · 难度:入门 · +10XP

C++20 协程 Promise 类型与自定义 Awaitable 对象

协程通过 promise_type 控制行为,包括初始挂起、返回值、异常处理等。自定义 awaitable 需要实现 await_readyawait_suspendawait_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() {}
};
Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 105 篇
0 完成
🔥 0