考虑以下代码:
coroutine_handle<> g_handle;
atomic<int> g_ready;
void worker_thread() {
if (++g_ready == 2) g_handle.resume();
}
struct Awaitable {
bool await_ready() const { return false; }
bool await_suspend(coroutine_handle<> h) {
g_handle = h;
if (++g_ready == 2) return false;
// worker_thread can call h.resume() at this point
return true;
}
void await_resume() {}
};
Future coroutine() {
Awaitable a;
std::thread(worker_thread).detach();
co_await a; // compiles as:
// if (a.await_suspend(h)) {
// // worker_thread can call h.resume() at this point
// return;
// }
}
这里worker_thread
可以h.resume();
在协程仍在执行时await_suspend
或在协程之间await_suspend()
和之间调用return
。
Coroutines TS说resume
只有在协程挂起时才能调用。
执行期间是否被视为暂停await_suspend
?