我有一个异步功能
void async_foo(A& a, B& b, C&c, function<void(X&, Y&)> callback);
Run Code Online (Sandbox Code Playgroud)
我想在无栈协程中使用它,所以我写
auto coro_foo(A& a, B& b, C& c, X& x) /* -> Y */ {
struct Awaitable {
bool await_ready() const noexcept { return false; }
bool await_suspend(coroutine_handle<> h) {
async_foo(*a_, *b_, *c_, [this, h](X& x, Y& y){
*x_ = std::move(x);
y_ = std::move(y);
h.resume();
});
}
Y await_resume() {
return std::move(y);
}
A* a_; B* b_; C* c_; X* x_; Y y_;
};
return Awaitable{&a, &b, &c, &x};
}
Run Code Online (Sandbox Code Playgroud)
然后我可以像这样使用它:
Y y = co_await coro_foo(a, b, c, x);
Run Code Online (Sandbox Code Playgroud)
和编译器会将其重写为:
auto e = coro_foo(a, b, c, x);
if (!e.await_ready()) {
<suspend>
if (e.await_suspend(h)) return;
resume-point:
<resume>
}
Y y = e.await_resume();
Run Code Online (Sandbox Code Playgroud)
这样,协程将保持a_,b_以及c_当它的悬挂,当只需要保留,直到我们得到coroutine_handle在await_suspend(h).
(顺便说一下,我不确定我是否可以在这里继续引用这些参数.)
如果包装函数可以直接coroutine_handle作为参数获得,那将会更有效.
这可能是一个隐含的论点:
Promise f(coroutine_handle<> h);
co_await f();
Run Code Online (Sandbox Code Playgroud)
或者它可能是一个特殊的关键字参数:
Promise f(coroutine_handle<> h);
f(co_await);
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么吗?(其他开销不是那么大.)
当前的设计有一个重要的未来,即co_await采用通用表达式而不是调用表达式。
这允许我们编写如下代码:
auto f = coro_1();
co_await coro_2();
co_await f;
Run Code Online (Sandbox Code Playgroud)
我们可以并行运行两个或多个异步任务,然后等待它们。
因此, 的实现coro_1应该在其调用中开始工作,而不是在 中await_suspend。
这也意味着应该有一个预先分配的内存来coro_1放置其结果,以及将coroutine_handle.
我们可以使用不可复制Awaitable和有保证的复制省略。
async_foo将从以下构造函数调用Awaitable:
auto coro_foo(A& a, B& b, C& c, X& x) /* -> Y */ {
struct Awaitable {
Awaitable(A& a, B& b, C& c, X& x) : x_(x) {
async_foo(a, b, c, [this](X& x, Y& y){
*x_ = std::move(x);
y_ = &y;
if (done_.exchange(true)) {
h.resume(); // Coroutine resumes inside of resume()
}
});
}
bool await_ready() const noexcept {
return done_;
}
bool await_suspend(coroutine_handle<> h) {
h_ = h;
return !done_.exchange(true);
}
Y await_resume() {
return std::move(*y_);
}
atomic<bool> done_;
coroutine_handle<> h_;
X* x_;
Y* y_;
};
return Awaitable(a, b, c, &x);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1421 次 |
| 最近记录: |