Ale*_*Dun 6 c++ c++20 c++-coroutine
我对 C++ 协程相当陌生。当我的应用程序关闭时,我希望能够给任何未完成的协同例程一个提示,表明我希望它们早点完成。我提出的一个解决方案/想法是在 Promise 上添加一个布尔值,然后我需要一种方法来从协同例程中检查该布尔值。
我拼凑了一个相当简单的解决方案(使用 co_await 来获取句柄),但这感觉像是一个混杂的东西——编译器应该已经可以从框架内访问句柄。我想知道是否有一个标准的内在函数允许访问句柄或承诺?或者是否有人想出了更干净、更好的解决方案?
struct co_gethandle_awaitable
{
co_gethandle_awaitable()
: m_hWaiter(nullptr)
{
}
bool await_ready() const noexcept
{
return m_hWaiter != nullptr;
}
void await_suspend(std::coroutine_handle<> hWaiter) noexcept
{
m_hWaiter = hWaiter;
m_hWaiter.resume();
}
void await_resume() noexcept
{
}
std::coroutine_handle<> m_hWaiter;
};
coroutine_ref<void> MyFunc()
{
// get my coroutine handle. Ideally this would be a helper function
// but then it would have to be awaitable, which would add further cost.
co_gethandle_awaitable obj;
co_await obj;
std::coroutine_handle<> hMe = obj.m_hWaiter;
// loop.
{
// do work.
if (is_cancelled(hMe))
break;
}
co_return;
}
Run Code Online (Sandbox Code Playgroud)