374 lines
12 KiB
C++
374 lines
12 KiB
C++
#pragma once
|
|
|
|
#include <Void/Async/Detail/Types.hpp>
|
|
#include <Void/Async/MpscQueue.hpp>
|
|
#include <Void/Async/Task.hpp>
|
|
|
|
#include <atomic>
|
|
#include <coroutine>
|
|
#include <cstddef>
|
|
#include <exception>
|
|
#include <expected>
|
|
#include <optional>
|
|
|
|
namespace Void::Async
|
|
{
|
|
|
|
class Executor;
|
|
|
|
namespace detail
|
|
{
|
|
struct ActiveExecutorFrame {
|
|
const Executor* exec{nullptr};
|
|
const ActiveExecutorFrame* prev{nullptr};
|
|
|
|
[[nodiscard]] static inline const ActiveExecutorFrame*& head() noexcept
|
|
{
|
|
thread_local const ActiveExecutorFrame* slot = nullptr;
|
|
return slot;
|
|
}
|
|
};
|
|
|
|
class ExecutorThreadGuard
|
|
{
|
|
public:
|
|
explicit ExecutorThreadGuard(const Executor* exec) noexcept
|
|
: frame_{exec, ActiveExecutorFrame::head()}
|
|
{
|
|
ActiveExecutorFrame::head() = &frame_;
|
|
}
|
|
|
|
~ExecutorThreadGuard()
|
|
{
|
|
ActiveExecutorFrame::head() = frame_.prev;
|
|
}
|
|
|
|
ExecutorThreadGuard(const ExecutorThreadGuard&) = delete;
|
|
ExecutorThreadGuard& operator=(const ExecutorThreadGuard&) = delete;
|
|
|
|
private:
|
|
ActiveExecutorFrame frame_;
|
|
};
|
|
} // namespace detail
|
|
|
|
// ── 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;
|
|
|
|
// Bounded non-blocking admission. Subclasses may override with queue caps.
|
|
[[nodiscard]] virtual std::expected<void, AdmissionError>
|
|
try_post(std::coroutine_handle<> handle)
|
|
{
|
|
if (!handle) {
|
|
return std::unexpected{AdmissionError::invalid_argument};
|
|
}
|
|
post(handle);
|
|
return {};
|
|
}
|
|
|
|
// Reserved lane for resuming waiting/joining continuations without normal
|
|
// work-queue backpressure rejections.
|
|
virtual void post_completion(std::coroutine_handle<> handle)
|
|
{
|
|
if (handle) {
|
|
post(handle);
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] virtual bool is_executor_thread() const noexcept
|
|
{
|
|
for (const auto* f = detail::ActiveExecutorFrame::head();
|
|
f != nullptr;
|
|
f = f->prev) {
|
|
if (f->exec == this) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
[[nodiscard]] virtual bool supports_reservation() const noexcept { return false; }
|
|
|
|
[[nodiscard]] virtual std::expected<void, AdmissionError> try_reserve_slot()
|
|
{
|
|
return {};
|
|
}
|
|
|
|
virtual void commit_reserved(std::coroutine_handle<> handle)
|
|
{
|
|
post_completion(handle);
|
|
}
|
|
|
|
virtual void release_reserved() noexcept {}
|
|
|
|
[[nodiscard]] virtual bool has_background_workers() const noexcept { return true; }
|
|
};
|
|
|
|
// ── 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:
|
|
explicit ManualExecutor(std::size_t max_queue = 0) noexcept
|
|
: max_queue_(max_queue)
|
|
{
|
|
}
|
|
|
|
void post(std::coroutine_handle<> handle) override
|
|
{
|
|
if (!handle) {
|
|
return;
|
|
}
|
|
pending_normal_.fetch_add(1, std::memory_order_acq_rel);
|
|
queue_.push(handle);
|
|
}
|
|
|
|
[[nodiscard]] std::expected<void, AdmissionError>
|
|
try_post(std::coroutine_handle<> handle) override
|
|
{
|
|
if (!handle) {
|
|
return std::unexpected{AdmissionError::invalid_argument};
|
|
}
|
|
auto reserved = try_reserve_slot();
|
|
if (!reserved.has_value()) {
|
|
return reserved;
|
|
}
|
|
queue_.push(handle);
|
|
return {};
|
|
}
|
|
|
|
void post_completion(std::coroutine_handle<> handle) override
|
|
{
|
|
if (!handle) {
|
|
return;
|
|
}
|
|
completion_queue_.push(handle);
|
|
}
|
|
|
|
[[nodiscard]] bool supports_reservation() const noexcept override { return true; }
|
|
|
|
[[nodiscard]] std::expected<void, AdmissionError> try_reserve_slot() override
|
|
{
|
|
std::size_t cur = pending_normal_.load(std::memory_order_acquire);
|
|
for (;;) {
|
|
if (!accepting_.load(std::memory_order_acquire)) {
|
|
return std::unexpected{AdmissionError::stopped};
|
|
}
|
|
if (max_queue_ != 0 && cur >= max_queue_) {
|
|
return std::unexpected{AdmissionError::overloaded};
|
|
}
|
|
if (pending_normal_.compare_exchange_weak(
|
|
cur,
|
|
cur + 1,
|
|
std::memory_order_acq_rel,
|
|
std::memory_order_acquire)) {
|
|
return {};
|
|
}
|
|
}
|
|
}
|
|
|
|
void commit_reserved(std::coroutine_handle<> handle) override
|
|
{
|
|
if (!handle) {
|
|
pending_normal_.fetch_sub(1, std::memory_order_acq_rel);
|
|
return;
|
|
}
|
|
queue_.push(handle);
|
|
}
|
|
|
|
void release_reserved() noexcept override
|
|
{
|
|
pending_normal_.fetch_sub(1, std::memory_order_acq_rel);
|
|
}
|
|
|
|
[[nodiscard]] bool has_background_workers() const noexcept override { return false; }
|
|
|
|
void shutdown() noexcept
|
|
{
|
|
accepting_.store(false, std::memory_order_release);
|
|
}
|
|
|
|
[[nodiscard]] bool is_accepting() const noexcept
|
|
{
|
|
return accepting_.load(std::memory_order_acquire);
|
|
}
|
|
|
|
[[nodiscard]] std::size_t pending_normal() const noexcept
|
|
{
|
|
return pending_normal_.load(std::memory_order_acquire);
|
|
}
|
|
|
|
[[nodiscard]] std::size_t max_queue() const noexcept { return max_queue_; }
|
|
|
|
// Resume one pending coroutine. Returns false if none was pending.
|
|
bool run_one()
|
|
{
|
|
if (auto c = completion_queue_.try_pop(); c.has_value()) {
|
|
detail::ExecutorThreadGuard guard{this};
|
|
c->resume();
|
|
return true;
|
|
}
|
|
auto h = queue_.try_pop();
|
|
if (!h) {
|
|
return false;
|
|
}
|
|
pending_normal_.fetch_sub(1, std::memory_order_acq_rel);
|
|
detail::ExecutorThreadGuard guard{this};
|
|
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 completion_queue_.empty() && queue_.empty();
|
|
}
|
|
|
|
private:
|
|
std::size_t max_queue_{0};
|
|
std::atomic<std::size_t> pending_normal_{0};
|
|
std::atomic<bool> accepting_{true};
|
|
MpscQueue<std::coroutine_handle<>> queue_{};
|
|
MpscQueue<std::coroutine_handle<>> completion_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<void> 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.
|
|
//
|
|
// The wrapper starts suspended and is posted only after its ramp function has
|
|
// returned. An eagerly started wrapper that posted itself from its first
|
|
// co_await could be resumed and destroyed by an executor worker while the
|
|
// spawning thread was still inside the ramp (data race reported by TSan when
|
|
// spawning from a non-worker thread onto a multi-worker executor; W11).
|
|
|
|
namespace Detail
|
|
{
|
|
struct DetachedTask {
|
|
struct promise_type {
|
|
DetachedTask get_return_object() noexcept
|
|
{
|
|
return DetachedTask{
|
|
std::coroutine_handle<promise_type>::from_promise(*this)};
|
|
}
|
|
std::suspend_always initial_suspend() noexcept { return {}; }
|
|
std::suspend_never final_suspend() noexcept { return {}; }
|
|
void return_void() noexcept {}
|
|
void unhandled_exception() noexcept { std::terminate(); }
|
|
};
|
|
|
|
std::coroutine_handle<promise_type> handle{};
|
|
};
|
|
|
|
inline DetachedTask spawn_impl(Coro::Task<void> task)
|
|
{
|
|
co_await std::move(task);
|
|
}
|
|
} // namespace Detail
|
|
|
|
inline void spawn(Executor& executor, Coro::Task<void> task)
|
|
{
|
|
Detail::DetachedTask detached = Detail::spawn_impl(std::move(task));
|
|
executor.post(detached.handle);
|
|
}
|
|
|
|
struct ScheduleStatusAwaiter {
|
|
Executor& executor;
|
|
OperationOptions options{};
|
|
const Void::Time::MonotonicClock* clock{&Void::Time::SystemMonotonicClock::instance()};
|
|
Void::Result::Result<void> pre_outcome{};
|
|
|
|
[[nodiscard]] bool await_ready() noexcept
|
|
{
|
|
if (options.stop.stop_requested()) {
|
|
pre_outcome = std::unexpected{make_async_error(
|
|
AsyncErrorCode::cancelled, "schedule_on cancelled before scheduling")};
|
|
return true;
|
|
}
|
|
if (is_deadline_expired(options, *clock)) {
|
|
pre_outcome = std::unexpected{make_async_error(
|
|
AsyncErrorCode::timeout, "schedule_on deadline expired before scheduling")};
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
[[nodiscard]] bool await_suspend(std::coroutine_handle<> handle)
|
|
{
|
|
const auto post_res = executor.try_post(handle);
|
|
if (!post_res.has_value()) {
|
|
pre_outcome = std::unexpected{make_async_error(
|
|
post_res.error(), "schedule_on rejected by executor")};
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
[[nodiscard]] Void::Result::Result<void> await_resume() noexcept
|
|
{
|
|
if (!pre_outcome.has_value()) {
|
|
return pre_outcome;
|
|
}
|
|
if (options.stop.stop_requested()) {
|
|
return std::unexpected{make_async_error(
|
|
AsyncErrorCode::cancelled, "schedule_on cancelled before execution")};
|
|
}
|
|
if (is_deadline_expired(options, *clock)) {
|
|
return std::unexpected{make_async_error(
|
|
AsyncErrorCode::timeout, "schedule_on deadline expired before execution")};
|
|
}
|
|
return {};
|
|
}
|
|
};
|
|
|
|
[[nodiscard]] inline ScheduleStatusAwaiter schedule_on(
|
|
Executor& executor,
|
|
OperationOptions options,
|
|
const Void::Time::MonotonicClock& clock = Void::Time::SystemMonotonicClock::instance()) noexcept
|
|
{
|
|
return ScheduleStatusAwaiter{executor, std::move(options), &clock};
|
|
}
|
|
|
|
} // namespace Void::Async
|