封装C++20协程 基本概念 在C++20中,只要函数返回值是Task类型,并使用co_return返回,该函数就自动成为一个协程函数。
Task不仅仅是一个”配置文件”,它还承担着协程的核心管理职责。
核心原理 协程的执行控制 一个返回Task的函数本身就是协程,其内部代码会在以下情况下异步执行:
co_await 语句控制
co_return 语句控制
恢复协程的两种方式
内部恢复:
通过handle.resume()
由异步等待操作触发(如Delay的await_suspend)
外部恢复:
通过task2.resume()显式调用
主动从外部恢复协程执行
这两种方式都会立即恢复协程并从挂起点继续执行,最终到达co_return。
实践发现 在实际使用中发现一个有趣的现象:
注释掉handle.resume()不影响程序运行
但注释掉main函数中的resume()会导致程序卡住编译命令 1 g++ -o test -std=c++20 test.cpp
完整头文集 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 #pragma once #include <coroutine> #include <exception> #include <concepts> #include <type_traits> template <typename T>class Task {public : struct promise_type { T value_; std::exception_ptr exception_; Task get_return_object () { return Task (std::coroutine_handle<promise_type>::from_promise (*this )); } std::suspend_always initial_suspend () noexcept { return {}; } std::suspend_always final_suspend () noexcept { return {}; } void return_value (T value) { value_ = std::move (value); } void unhandled_exception () { exception_ = std::current_exception (); } }; bool await_ready () const noexcept { return false ; } void await_suspend (std::coroutine_handle<> handle) const noexcept { waiting_handle_ = handle; handle_.resume (); } T await_resume () { if (handle_.promise ().exception_) { std::rethrow_exception (handle_.promise ().exception_); } return std::move (handle_.promise ().value_); } Task (std::coroutine_handle<promise_type> handle) : handle_ (handle) {} ~Task () { if (handle_) handle_.destroy (); } Task (const Task&) = delete ; Task& operator =(const Task&) = delete ; Task (Task&& other) noexcept : handle_ (other.handle_) { other.handle_ = nullptr ; } Task& operator =(Task&& other) noexcept { if (this != &other) { if (handle_) handle_.destroy (); handle_ = other.handle_; other.handle_ = nullptr ; } return *this ; } T get () { if (handle_.promise ().exception_) std::rethrow_exception (handle_.promise ().exception_); return std::move (handle_.promise ().value_); } void resume () { handle_.resume (); } bool done () const { return handle_.done (); } private : std::coroutine_handle<promise_type> handle_; mutable std::coroutine_handle<> waiting_handle_ = nullptr ; }; template <>class Task <void > {public : struct promise_type { std::exception_ptr exception_; Task<void > get_return_object () { return Task <void >(std::coroutine_handle<promise_type>::from_promise (*this )); } std::suspend_always initial_suspend () noexcept { return {}; } std::suspend_always final_suspend () noexcept { return {}; } void return_void () {} void unhandled_exception () { exception_ = std::current_exception (); } }; bool await_ready () const noexcept { return false ; } void await_suspend (std::coroutine_handle<> handle) const noexcept { waiting_handle_ = handle; handle_.resume (); } void await_resume () { if (handle_.promise ().exception_) { std::rethrow_exception (handle_.promise ().exception_); } } Task (std::coroutine_handle<promise_type> handle) : handle_ (handle) {} ~Task () { if (handle_) handle_.destroy (); } Task (const Task&) = delete ; Task& operator =(const Task&) = delete ; Task (Task&& other) noexcept : handle_ (other.handle_) { other.handle_ = nullptr ; } Task& operator =(Task&& other) noexcept { if (this != &other) { if (handle_) handle_.destroy (); handle_ = other.handle_; other.handle_ = nullptr ; } return *this ; } void get () { if (handle_.promise ().exception_) std::rethrow_exception (handle_.promise ().exception_); } void resume () { handle_.resume (); } bool done () const { return handle_.done (); } private : std::coroutine_handle<promise_type> handle_; mutable std::coroutine_handle<> waiting_handle_ = nullptr ; }; ```cpp #include "MyCoroutine.h" #include <iostream> #include <chrono> #include <thread> class Delay { std::chrono::milliseconds duration_; public : explicit Delay (std::chrono::milliseconds duration) : duration_(duration) { } bool await_ready () const noexcept { return false ; } void await_suspend (std::coroutine_handle<> handle) { std::thread ([handle, this ]() { std::this_thread::sleep_for (duration_); }).detach (); } void await_resume () const noexcept {} }; Task<int > simple_task () { std::cout << "开始执行任务" << std::endl; co_return 42 ; } Task<std::string> delayed_task () { std::cout << "开始延迟任务" << std::endl; co_await Delay (std::chrono::milliseconds(4000 )) ; co_return "完成" ; } Task<void > combined_tasks () { auto result1 = co_await simple_task (); std::cout << "第一个任务结果: " << result1 << std::endl; auto result2 = co_await delayed_task (); std::cout << "第二个任务结果: " << result2 << std::endl; co_return ; } int main () { auto task1 = simple_task (); while (!task1. done ()) { task1. resume (); } std::cout << "简单任务结果: " << task1. get () << std::endl; auto task2 = delayed_task (); while (!task2. done ()) { task2. resume (); } std::cout << "延迟任务结果: " << task2. get () << std::endl; auto task3 = combined_tasks (); while (!task3. done ()) { task3. resume (); } task3. get (); return 0 ; }
```
注意事项
协程函数必须:
恢复机制选择:
内部恢复适合自动触发的场景
外部恢复适合需要手动控制的场景
性能考虑:
协程切换有一定开销
适合IO密集型任务
不适合CPU密集型计算