[英]Can I call coroutine_handle::resume during await_suspend?
Consider the following code: 考虑以下代码:
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;
// }
}
Here the worker_thread
can call h.resume();
这里
worker_thread
可以调用h.resume();
when the coroutine is still executing await_suspend
or between await_suspend()
and return
in the coroutine. 当协程仍在执行
await_suspend
或在await_suspend()
之间并return
协程时。
The Coroutines TS says that resume
can be called only when a coroutine is suspended. 协程TS表示,只有在暂停协程时才能调用
resume
。
Is it considered suspended during the execution of await_suspend
? 在执行
await_suspend
期间是否认为它已暂停?
Yes, the text of the linked Coroutines TS states, 5.3.8 paragraph 3-5. 是的,链接的协程TS文本为5.3.8第3-5段。 Emphasis mine:
重点:
5 The await-expression evaluates the await-ready expression, then: —
5 await-expression计算等待就绪的表达式,然后:
(5.1) If the result is false , the coroutine is considered suspended.
(5.1)如果结果为假,则协程被视为已暂停。 Then, the await-suspend expression is evaluated.
然后,计算等待挂起表达式。 If that expression has type bool and evaluates to false , the coroutine is resumed.
如果该表达式的类型为bool且计算结果为false,则协程将恢复。 If that expression exits via an exception, the exception is caught, the coroutine is resumed, and the exception is immediately re-thrown (15.1).
如果该表达式通过异常退出,则捕获该异常,恢复协程,并立即重新抛出该异常(15.1)。 Otherwise, control flow returns to the current caller or resumer (8.4.4) without exiting any scopes (6.6).
否则,控制流将返回当前的调用者或恢复者(8.4.4),而不会退出任何范围(6.6)。 —
-
So you may resume the coroutine from another thread, as long as you guarantee that exiting await-suspend does not cause a double resume, or destruction of the coroutine 因此,只要保证退出退出挂起不会引起重复恢复或破坏协程,就可以从其他线程恢复协程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.