Can I call coroutine_handle::resume during await_suspend?

Viewed 918

Consider the following code:

coroutine_handle<> g_handle;
atomic<int> g_ready;

void worker_thread() {
  if (++g_ready == 2) g_handle.resume();
}

struct Awaitable {
  bool await_ready() const { return false; }
  bool await_suspend(coroutine_handle<> h) {
    g_handle = h;
    if (++g_ready == 2) return false;
    // worker_thread can call h.resume() at this point
    return true;
  }
  void await_resume() {}
};

Future coroutine() {
  Awaitable a;
  std::thread(worker_thread).detach();
  co_await a; // compiles as:
              // if (a.await_suspend(h)) {
              //   // worker_thread can call h.resume() at this point
              //   return;
              // }
}

Here the worker_thread can call h.resume(); when the coroutine is still executing await_suspend or between await_suspend() and return in the coroutine.

The Coroutines TS says that resume can be called only when a coroutine is suspended.

Is it considered suspended during the execution of await_suspend?

1 Answers
Related