#pragma once #include #include #include #include #include namespace Void::Async { // ── Executor ────────────────────────────────────────────────────────────────── // Minimal scheduling interface bridging Coro::Task to a driving thread. // post() must be safe to call from any thread. class Executor { public: virtual ~Executor() = default; // Schedule a coroutine for resumption on this executor. Thread-safe. virtual void post(std::coroutine_handle<> handle) = 0; }; // ── ManualExecutor ──────────────────────────────────────────────────────────── // An executor whose queue is drained explicitly by its owning thread. // post() is lock-free from any thread; run_one()/drain() must only be // called from a single consumer thread (typically the owner's loop). class ManualExecutor final : public Executor { public: void post(std::coroutine_handle<> handle) override { queue_.push(handle); } // Resume one pending coroutine. Returns false if none was pending. bool run_one() { auto h = queue_.try_pop(); if (!h) { return false; } h->resume(); return true; } // Resume pending coroutines until the queue drains. Returns how many // coroutines were resumed (including ones posted while draining). std::size_t drain() { std::size_t count = 0; while (run_one()) { ++count; } return count; } [[nodiscard]] bool empty() const noexcept { return queue_.empty(); } private: MpscQueue> queue_; }; // ── schedule_on ─────────────────────────────────────────────────────────────── // Awaitable that re-schedules the awaiting coroutine onto an executor: // // co_await schedule_on(executor); // resumes on the executor's thread struct ScheduleAwaiter { Executor& executor; [[nodiscard]] bool await_ready() const noexcept { return false; } void await_suspend(std::coroutine_handle<> h) const { executor.post(h); } void await_resume() const noexcept {} }; [[nodiscard]] inline ScheduleAwaiter schedule_on(Executor& executor) { return ScheduleAwaiter{executor}; } // ── spawn ───────────────────────────────────────────────────────────────────── // Launch a Task detached, driven on the given executor. The wrapper // coroutine owns the task; its frame self-destroys on completion. An // exception escaping the task terminates (there is no awaiter to receive // it) — handle errors inside the task. namespace Detail { struct DetachedTask { struct promise_type { DetachedTask get_return_object() noexcept { return {}; } std::suspend_never initial_suspend() noexcept { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void return_void() noexcept {} void unhandled_exception() noexcept { std::terminate(); } }; }; inline DetachedTask spawn_impl(Executor& executor, Coro::Task task) { co_await schedule_on(executor); co_await std::move(task); } } // namespace Detail inline void spawn(Executor& executor, Coro::Task task) { Detail::spawn_impl(executor, std::move(task)); } } // namespace Void::Async