DetachedCoroutine 似乎没有必要? #148
-
当前逻辑: struct FinalAwaiter {
bool await_ready() const noexcept { return false; }
template <typename PromiseType>
auto await_suspend(std::coroutine_handle<PromiseType> h) noexcept {
return h.promise()._continuation;
}
void await_resume() noexcept {}
};
// Lazy:
template <typename F>
void start(F&& callback) {
// callback should take a single Try<T> as parameter, return value will
// be ignored. a detached coroutine will not suspend at initial/final
// suspend point.
auto launchCoro = [](Lazy lazy,
std::decay_t<F> cb) -> detail::DetachedCoroutine {
cb(std::move(co_await lazy.coAwaitTry()));
};
[[maybe_unused]] auto detached =
launchCoro(std::move(*this), std::forward<F>(callback));
} 是不是可以简化成如下:移除 struct FinalAwaiter {
bool await_ready() const noexcept { return false; }
template <typename PromiseType>
std::coroutine_handle<> await_suspend(std::coroutine_handle<PromiseType> h) noexcept {
if (auto continue_h = h.promise()._continuation) {
return continue_h;
}
return std::noop_coroutine();
}
void await_resume() noexcept {}
};
// Lazy:
template <typename F>
void start(F&& callback) {
if (!isReady()) {
_coro.resume(); // 激活当前挂起的协程
}
callback(coAwaitTry().await_resume()); // 获取协程运行结果
} |
Beta Was this translation helpful? Give feedback.
Answered by
ChuanqiXu9
Sep 15, 2022
Replies: 3 comments 5 replies
-
这种情况是不可以的,执行 coAwaitTry 时 Lazy 不一定执行完成。同时这种写法无法处理异常。 |
Beta Was this translation helpful? Give feedback.
1 reply
-
hmmm 你可以试试跑跑测试 |
Beta Was this translation helpful? Give feedback.
1 reply
-
DetachedCoroutine 最大的作用是提供协程环境,这和无栈协程的工作机制有关系,你可能需要再了解一下。另外跑测试来验证会更快些。 |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
ChuanqiXu9
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DetachedCoroutine 最大的作用是提供协程环境,这和无栈协程的工作机制有关系,你可能需要再了解一下。另外跑测试来验证会更快些。