1. 何是协程?
协程是一种轻量级的子程序,能够在执行过程中暂停和恢复。与传统的线程相比,协程不需要上下文切换的成本,只需要保存当前的栈帧信息即可。C++20 标准在 `
` 头文件中引入了协程支持,使得异步编程变得更加直观。 ## 2. 协程的基本组成 | 术语 | 含义 | |——|——| | `co_await` | 暂停协程,等待一个 awaitable 对象完成 | | `co_yield` | 暂停协程并返回一个值给调用者 | | `co_return` | 结束协程并返回最终结果 | | `std::coroutine_handle` | 对协程实例的句柄,用于控制其生命周期 | | `promise_type` | 协程的返回值包装器,定义了协程的行为 | ## 3. 一个完整的协程例子 下面的例子演示了一个生成整数序列的协程,并用 `co_await` 与自定义 awaitable 对象一起模拟异步延迟。 “`cpp #include #include #include #include #include struct AsyncSleep { std::chrono::milliseconds duration; AsyncSleep(std::chrono::milliseconds d) : duration(d) {} bool await_ready() const noexcept { return false; } void await_suspend(std::coroutine_handle h) const noexcept { std::thread([h, dur = duration]() mutable { std::this_thread::sleep_for(dur); h.resume(); }).detach(); } void await_resume() const noexcept {} }; struct Generator { struct promise_type { int current_value; Generator get_return_object() { return Generator{std::coroutine_handle ::from_promise(*this)}; } std::suspend_always initial_suspend() { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void unhandled_exception() { std::terminate(); } void return_void() {} std::suspend_always yield_value(int value) { current_value = value; return {}; } }; std::coroutine_handle handle; explicit Generator(std::coroutine_handle h) : handle(h) {} ~Generator() { if (handle) handle.destroy(); } bool next() { if (!handle.done()) { handle.resume(); return !handle.done(); } return false; } int value() const { return handle.promise().current_value; } }; Generator number_sequence() { for (int i = 0; i