I'm fairly new to C++ coroutines. When my app shuts down, I'd like to be able to give any outstanding co-routines a hint that I'd prefer they finished early. One solution/idea I came up with was to put a bool on the promise, and then I need a way to check the bool from within the co-routine.
I pieced together a fairly simple solution (using co_await to get the handle), but this feels like a kluge -- the compiler ought to already have access to the handle from within the frame. I'm wondering if there is a standard intrinsic that allows access to the handle or the promise? Or if anyone has come up with a cleaner, better solution?
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;
}