2

如果我的措辞不清楚,这是代码。

struct token {};

struct resumable {
    struct promise_type {
        auto get_return_object() {
            return coroutine_handle<promise_type>::from_promise(*this);
        }
        suspend_never initial_suspend() { return {}; }
        suspend_always final_suspend() { return {}; }

        auto await_transform(token)
        {
            struct awaiter {
                awaiter(promise_type& p) : m_promise(p) {}
                bool await_ready() { return false; }
                void await_suspend(coroutine_handle<>) {}
                int await_resume() {
                    int _result = 5;
                    return _result;
                }
                promise_type& m_promise;
            };
            return awaiter(*this);
        }
    };

    bool resume() {
        if (!m_handle.done()) {
            m_handle.resume();
        }
        return !m_handle.done();
    }

    resumable(coroutine_handle<promise_type> h) : m_handle(h) {}

private:
    coroutine_handle<promise_type> m_handle;
};

void someAsyncKernelApi(void* callbackContext)
{
    // When async work is done, enqueues callbackContext into the completion queue.
}

token WrappedAsyncKernelApi(void* callbackContext)
{
    someAsyncKernelApi(callbackContext);
    return token{};
}

resumable coro()
{
    int _async_result = co_await WrappedAsyncKernelApi(/* Is it possible to pass address of this own 
                                                          spawned coroutine to get called later on? 
                                                          Same address the pointer "r_ptr" at main 
                                                          is pointing to*/);
}

int main()
{
    resumable* r_ptr = new auto(coro());
}

我现在能想到的几个解决方案要么是在生成协程时初始挂起并将指针存储在任意结构中并从该存储的结构中传递,要么在第一次等待时等待可恢复的指针。但我觉得有更清洁的方法可以做到这一点..有吗?

4

0 回答 0