605 lines
21 KiB
C++
605 lines
21 KiB
C++
#pragma once
|
|
|
|
#include <Void/Async/Detail/Types.hpp>
|
|
#include <Void/Async/Executor.hpp>
|
|
#include <Void/Functional/Error.hpp>
|
|
#include <Void/Functional/Result.hpp>
|
|
|
|
#include <condition_variable>
|
|
#include <coroutine>
|
|
#include <cstddef>
|
|
#include <cstdint>
|
|
#include <cstdio>
|
|
#include <deque>
|
|
#include <exception>
|
|
#include <expected>
|
|
#include <functional>
|
|
#include <memory>
|
|
#include <mutex>
|
|
#include <optional>
|
|
#include <string>
|
|
#include <system_error>
|
|
#include <thread>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
// ── ThreadExecutor ────────────────────────────────────────────────────────────
|
|
// A thread-backed `Executor` with a bounded normal lane and a reserved,
|
|
// prioritized completion lane (C-03/C-04).
|
|
//
|
|
// Lifecycle
|
|
// create() builds the object and starts NO thread. Admission before start()
|
|
// queues normally; nothing runs until start() succeeds.
|
|
// start() once. `before_worker_start(i)` (a fault-injection hook, called on
|
|
// the starting thread with no lock held) and every `std::thread`
|
|
// construction share ONE failure path: workers that were already
|
|
// started are told to exit WITHOUT dequeuing anything and are
|
|
// joined, start() returns the error and may be retried. start()
|
|
// after a successful start, or after close()/join(), returns
|
|
// `invalid_argument`.
|
|
// close() normal admission (`try_post`, `try_reserve_slot`) returns
|
|
// `stopped`; a legacy `post()` is redirected onto the completion
|
|
// lane (counted); `post_completion` keeps working. Reservations
|
|
// taken before close() stay binding.
|
|
// join() close() + drain BOTH lanes until they are empty with nothing
|
|
// running and no reservation outstanding, then joins the worker
|
|
// threads. Safe to call repeatedly and concurrently (later callers
|
|
// wait for the first join to finish). On an executor thread it
|
|
// returns `AdmissionError::self_join`. When no worker is running
|
|
// (never started, or start() failed) join() drains both lanes
|
|
// INLINE on the caller under `ExecutorThreadGuard` (counted as
|
|
// `inline_after_join`) and never waits for workers; it still waits
|
|
// for an outstanding reservation, which another thread must commit
|
|
// or release.
|
|
// after join(): `post` / `post_completion` / `commit_reserved` resume the
|
|
// handle inline on the caller (counted `inline_after_join`);
|
|
// a handle is never dropped. `try_post` / `try_reserve_slot`
|
|
// return `stopped`. The switch to inline mode happens under the
|
|
// executor mutex in the same critical section that observes
|
|
// quiescence, so no handle can be stranded between the two modes.
|
|
// ~ThreadExecutor without a prior join() is close() + join(). Destroying the
|
|
// executor on one of its own executor threads (a worker, or a
|
|
// thread currently resuming a handle inline) prints a diagnostic
|
|
// to stderr and calls std::terminate.
|
|
//
|
|
// Bound
|
|
// `admitted()` = queued + running (normal lane) + reserved. `try_post` and
|
|
// `try_reserve_slot` return `overloaded` once `admitted() >= max_admitted`.
|
|
// A slot is released only after the resumed handle returns. A reservation
|
|
// counts in the bound until it is committed or released. Legacy `post()`
|
|
// never rejects (it is counted and may exceed the bound). The completion
|
|
// lane is not bounded and not counted in `admitted()`.
|
|
//
|
|
// Drain policy
|
|
// There is NO drain cap (C-03 forbids abandoning a frame). A handle that
|
|
// keeps re-posting itself prevents join() from returning; that is a caller
|
|
// error. A handle must not let an exception escape `resume()` (the worker
|
|
// would std::terminate). A reservation that is never committed or released
|
|
// prevents join() from returning (caller error).
|
|
//
|
|
// Snapshots: `idle()`, `admitted()` and `stats()` are point-in-time snapshots.
|
|
// `has_background_workers()` is the constant `true` (the design intent is a
|
|
// threaded executor; start() must have succeeded for work to make progress).
|
|
|
|
namespace Void::Async
|
|
{
|
|
|
|
struct ThreadExecutorOptions {
|
|
// Number of worker threads; zero is rejected by create().
|
|
std::size_t workers{1};
|
|
// Bound on queued + running normal-lane work (+ reservations); >= 1.
|
|
std::size_t max_admitted{4096};
|
|
// Called once per worker, on the starting thread with no lock held, before
|
|
// that worker's std::thread is created. An error (or a thrown exception)
|
|
// aborts start() through the shared failure path.
|
|
std::function<Void::Result::Result<void>(std::size_t)> before_worker_start{};
|
|
};
|
|
|
|
struct ThreadExecutorStats {
|
|
std::size_t queued{0}; // normal lane, not yet running
|
|
std::size_t running{0}; // handles being resumed now (both lanes)
|
|
std::size_t completion_queued{0}; // completion lane, not yet running
|
|
std::uint64_t rejected{0}; // try_post / try_reserve_slot -> overloaded
|
|
std::uint64_t legacy_posts{0}; // every post() call
|
|
std::uint64_t inline_after_join{0}; // handles resumed inline on a caller
|
|
};
|
|
|
|
class ThreadExecutor final : public Executor
|
|
{
|
|
public:
|
|
// Errors: invalid_argument when workers == 0 or max_admitted == 0.
|
|
// Starts no thread.
|
|
[[nodiscard]] static Void::Result::Result<std::unique_ptr<ThreadExecutor>>
|
|
create(ThreadExecutorOptions options = {})
|
|
{
|
|
if (options.workers == 0) {
|
|
return std::unexpected{make_async_error(
|
|
AsyncErrorCode::invalid_argument,
|
|
"ThreadExecutor workers must be greater than zero")};
|
|
}
|
|
if (options.max_admitted == 0) {
|
|
return std::unexpected{make_async_error(
|
|
AsyncErrorCode::invalid_argument,
|
|
"ThreadExecutor max_admitted must be greater than zero")};
|
|
}
|
|
return std::unique_ptr<ThreadExecutor>(new ThreadExecutor(std::move(options)));
|
|
}
|
|
|
|
ThreadExecutor(const ThreadExecutor&) = delete;
|
|
ThreadExecutor& operator=(const ThreadExecutor&) = delete;
|
|
ThreadExecutor(ThreadExecutor&&) = delete;
|
|
ThreadExecutor& operator=(ThreadExecutor&&) = delete;
|
|
|
|
~ThreadExecutor() override
|
|
{
|
|
if (is_executor_thread()) {
|
|
std::fputs(
|
|
"Void::Async::ThreadExecutor destroyed on its own executor thread\n",
|
|
stderr);
|
|
std::terminate();
|
|
}
|
|
(void)join();
|
|
}
|
|
|
|
// Starts the workers. Errors: invalid_argument (after close(), join() or a
|
|
// successful start()), the hook's error, or backend_error (with the
|
|
// system code when a std::system_error was caught) when a thread could not
|
|
// be created. After an error no thread is left running and start() may be
|
|
// retried.
|
|
[[nodiscard]] Void::Result::Result<void> start()
|
|
{
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
if (closed_ || phase_ != Phase::created) {
|
|
return std::unexpected{make_async_error(
|
|
AsyncErrorCode::invalid_argument,
|
|
"ThreadExecutor::start after start, close or join")};
|
|
}
|
|
phase_ = Phase::starting;
|
|
}
|
|
|
|
std::optional<Void::Result::Error> failure;
|
|
try {
|
|
workers_.reserve(options_.workers);
|
|
for (std::size_t i = 0; i < options_.workers; ++i) {
|
|
if (options_.before_worker_start) {
|
|
auto hook = options_.before_worker_start(i);
|
|
if (!hook.has_value()) {
|
|
failure = std::move(hook.error());
|
|
break;
|
|
}
|
|
}
|
|
workers_.emplace_back([this] { worker_loop(); });
|
|
}
|
|
} catch (const std::system_error& e) {
|
|
failure = Void::Result::Error{
|
|
Void::Result::ErrorKind::internal,
|
|
std::string{"ThreadExecutor worker start failed: "} + e.what(),
|
|
Void::Result::ErrorCode{
|
|
Void::Result::kAsyncErrorDomain,
|
|
static_cast<std::int32_t>(AsyncErrorCode::backend_error)},
|
|
e.code()};
|
|
} catch (const std::exception& e) {
|
|
failure = make_async_error(
|
|
AsyncErrorCode::backend_error,
|
|
std::string{"ThreadExecutor worker start failed: "} + e.what());
|
|
} catch (...) {
|
|
failure = make_async_error(
|
|
AsyncErrorCode::backend_error,
|
|
"ThreadExecutor worker start failed: unknown exception");
|
|
}
|
|
|
|
if (failure.has_value()) {
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
abort_start_ = true;
|
|
}
|
|
work_cv_.notify_all();
|
|
for (auto& worker : workers_) {
|
|
worker.join();
|
|
}
|
|
workers_.clear();
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
abort_start_ = false;
|
|
phase_ = Phase::created;
|
|
}
|
|
state_cv_.notify_all();
|
|
return std::unexpected{std::move(*failure)};
|
|
}
|
|
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
phase_ = Phase::running;
|
|
}
|
|
work_cv_.notify_all();
|
|
state_cv_.notify_all();
|
|
return {};
|
|
}
|
|
|
|
// Legacy admission: never rejects and never drops the handle. Counted in
|
|
// `legacy_posts`; may exceed the bound. After close() the handle goes to
|
|
// the completion lane; after join() it is resumed inline on the caller.
|
|
void post(std::coroutine_handle<> handle) override
|
|
{
|
|
if (!handle) {
|
|
return;
|
|
}
|
|
bool run_inline = false;
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
if (inline_mode_) {
|
|
++legacy_posts_;
|
|
++inline_after_join_;
|
|
run_inline = true;
|
|
} else {
|
|
if (closed_) {
|
|
completion_.push_back(handle);
|
|
} else {
|
|
normal_.push_back(handle);
|
|
}
|
|
++legacy_posts_;
|
|
}
|
|
}
|
|
if (run_inline) {
|
|
resume_inline(handle);
|
|
} else {
|
|
wake_one();
|
|
}
|
|
}
|
|
|
|
// Bounded admission. Errors: invalid_argument (empty handle), stopped
|
|
// (after close()), overloaded (admitted() >= max_admitted).
|
|
[[nodiscard]] std::expected<void, AdmissionError>
|
|
try_post(std::coroutine_handle<> handle) override
|
|
{
|
|
if (!handle) {
|
|
return std::unexpected{AdmissionError::invalid_argument};
|
|
}
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
if (closed_) {
|
|
return std::unexpected{AdmissionError::stopped};
|
|
}
|
|
if (admitted_locked() >= options_.max_admitted) {
|
|
++rejected_;
|
|
return std::unexpected{AdmissionError::overloaded};
|
|
}
|
|
normal_.push_back(handle);
|
|
}
|
|
wake_one();
|
|
return {};
|
|
}
|
|
|
|
// Reserved lane: never rejected, prioritized over the normal lane and
|
|
// drained after close(). After join() the handle is resumed inline.
|
|
void post_completion(std::coroutine_handle<> handle) override
|
|
{
|
|
if (!handle) {
|
|
return;
|
|
}
|
|
bool run_inline = false;
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
if (inline_mode_) {
|
|
++inline_after_join_;
|
|
run_inline = true;
|
|
} else {
|
|
completion_.push_back(handle);
|
|
}
|
|
}
|
|
if (run_inline) {
|
|
resume_inline(handle);
|
|
} else {
|
|
wake_one();
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] bool supports_reservation() const noexcept override { return true; }
|
|
|
|
// Reserves one slot of the bound. Errors: stopped (after close()),
|
|
// overloaded (admitted() >= max_admitted). A reservation must be answered
|
|
// by commit_reserved() or release_reserved().
|
|
[[nodiscard]] std::expected<void, AdmissionError> try_reserve_slot() override
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
if (closed_) {
|
|
return std::unexpected{AdmissionError::stopped};
|
|
}
|
|
if (admitted_locked() >= options_.max_admitted) {
|
|
++rejected_;
|
|
return std::unexpected{AdmissionError::overloaded};
|
|
}
|
|
++reserved_;
|
|
return {};
|
|
}
|
|
|
|
// Turns a reservation into a queued handle. Binding even after close().
|
|
// If enqueuing throws (allocation failure) the reservation is still held
|
|
// and the caller must release_reserved() it. An empty handle releases the
|
|
// reservation.
|
|
void commit_reserved(std::coroutine_handle<> handle) override
|
|
{
|
|
if (!handle) {
|
|
release_reserved();
|
|
return;
|
|
}
|
|
bool run_inline = false;
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
if (inline_mode_) {
|
|
if (reserved_ > 0) {
|
|
--reserved_;
|
|
}
|
|
++inline_after_join_;
|
|
run_inline = true;
|
|
} else {
|
|
normal_.push_back(handle);
|
|
if (reserved_ > 0) {
|
|
--reserved_;
|
|
}
|
|
}
|
|
}
|
|
if (run_inline) {
|
|
resume_inline(handle);
|
|
} else {
|
|
wake_one();
|
|
}
|
|
}
|
|
|
|
void release_reserved() noexcept override
|
|
{
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
if (reserved_ > 0) {
|
|
--reserved_;
|
|
}
|
|
}
|
|
state_cv_.notify_all();
|
|
}
|
|
|
|
[[nodiscard]] bool has_background_workers() const noexcept override { return true; }
|
|
|
|
// Closes normal admission (see the class comment). Idempotent.
|
|
void close() noexcept
|
|
{
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
closed_ = true;
|
|
}
|
|
work_cv_.notify_all();
|
|
state_cv_.notify_all();
|
|
}
|
|
|
|
// close() + drain + join (see the class comment). Errors: self_join on an
|
|
// executor thread.
|
|
[[nodiscard]] Void::Result::Result<void> join()
|
|
{
|
|
if (is_executor_thread()) {
|
|
return std::unexpected{make_async_error(
|
|
AdmissionError::self_join,
|
|
"ThreadExecutor::join called from an executor thread")};
|
|
}
|
|
|
|
std::unique_lock lk{mu_};
|
|
closed_ = true;
|
|
for (;;) {
|
|
if (phase_ == Phase::joined) {
|
|
return {};
|
|
}
|
|
if (phase_ == Phase::starting || phase_ == Phase::joining) {
|
|
state_cv_.wait(lk, [this] {
|
|
return phase_ != Phase::starting && phase_ != Phase::joining;
|
|
});
|
|
continue;
|
|
}
|
|
break;
|
|
}
|
|
|
|
if (phase_ == Phase::running) {
|
|
phase_ = Phase::joining;
|
|
work_cv_.notify_all();
|
|
state_cv_.wait(lk, [this] { return quiescent_locked(); });
|
|
// Same critical section as the quiescence observation: from here
|
|
// every admission resumes inline on its caller.
|
|
inline_mode_ = true;
|
|
std::vector<std::thread> threads = std::move(workers_);
|
|
workers_.clear();
|
|
lk.unlock();
|
|
work_cv_.notify_all();
|
|
for (auto& worker : threads) {
|
|
worker.join();
|
|
}
|
|
lk.lock();
|
|
phase_ = Phase::joined;
|
|
lk.unlock();
|
|
state_cv_.notify_all();
|
|
return {};
|
|
}
|
|
|
|
// Phase::created: no worker exists. The joiner is the worker.
|
|
phase_ = Phase::joining;
|
|
for (;;) {
|
|
if (!completion_.empty() || !normal_.empty()) {
|
|
const bool from_completion = !completion_.empty();
|
|
std::coroutine_handle<> handle;
|
|
if (from_completion) {
|
|
handle = completion_.front();
|
|
completion_.pop_front();
|
|
} else {
|
|
handle = normal_.front();
|
|
normal_.pop_front();
|
|
}
|
|
++inline_after_join_;
|
|
run_locked(lk, handle, from_completion);
|
|
continue;
|
|
}
|
|
if (reserved_ == 0 && running_normal_ == 0 && running_completion_ == 0) {
|
|
break;
|
|
}
|
|
state_cv_.wait(lk, [this] {
|
|
return !completion_.empty() || !normal_.empty() ||
|
|
(reserved_ == 0 && running_normal_ == 0 &&
|
|
running_completion_ == 0);
|
|
});
|
|
}
|
|
inline_mode_ = true;
|
|
phase_ = Phase::joined;
|
|
lk.unlock();
|
|
state_cv_.notify_all();
|
|
return {};
|
|
}
|
|
|
|
// True when both lanes are empty and nothing is running (a snapshot).
|
|
[[nodiscard]] bool idle() const noexcept
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
return normal_.empty() && completion_.empty() && running_normal_ == 0 &&
|
|
running_completion_ == 0;
|
|
}
|
|
|
|
// queued + running (normal lane) + reserved (a snapshot).
|
|
[[nodiscard]] std::size_t admitted() const noexcept
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
return admitted_locked();
|
|
}
|
|
|
|
[[nodiscard]] ThreadExecutorStats stats() const noexcept
|
|
{
|
|
std::lock_guard lk{mu_};
|
|
return ThreadExecutorStats{
|
|
normal_.size(),
|
|
running_normal_ + running_completion_,
|
|
completion_.size(),
|
|
rejected_,
|
|
legacy_posts_,
|
|
inline_after_join_};
|
|
}
|
|
|
|
private:
|
|
enum class Phase : std::uint8_t {
|
|
created, // no worker; start() allowed
|
|
starting, // start() in progress
|
|
running, // workers live
|
|
joining, // join() in progress
|
|
joined // workers gone; inline mode
|
|
};
|
|
|
|
explicit ThreadExecutor(ThreadExecutorOptions options)
|
|
: options_(std::move(options))
|
|
{
|
|
}
|
|
|
|
[[nodiscard]] std::size_t admitted_locked() const noexcept
|
|
{
|
|
return normal_.size() + running_normal_ + reserved_;
|
|
}
|
|
|
|
[[nodiscard]] bool quiescent_locked() const noexcept
|
|
{
|
|
return normal_.empty() && completion_.empty() && running_normal_ == 0 &&
|
|
running_completion_ == 0 && reserved_ == 0;
|
|
}
|
|
|
|
void wake_one()
|
|
{
|
|
work_cv_.notify_one();
|
|
// A joiner without workers drains the lanes itself and waits for them
|
|
// on the state condition variable.
|
|
state_cv_.notify_all();
|
|
}
|
|
|
|
void resume_inline(std::coroutine_handle<> handle)
|
|
{
|
|
detail::ExecutorThreadGuard guard{this};
|
|
handle.resume();
|
|
}
|
|
|
|
// Resumes `handle` (already popped and not yet counted as running) with
|
|
// the lock released, then re-acquires it and releases the slot. The slot is
|
|
// released only after the handle returned (or threw).
|
|
void run_locked(std::unique_lock<std::mutex>& lk,
|
|
std::coroutine_handle<> handle,
|
|
bool from_completion)
|
|
{
|
|
if (from_completion) {
|
|
++running_completion_;
|
|
} else {
|
|
++running_normal_;
|
|
}
|
|
lk.unlock();
|
|
try {
|
|
detail::ExecutorThreadGuard guard{this};
|
|
handle.resume();
|
|
} catch (...) {
|
|
lk.lock();
|
|
finish_locked(from_completion);
|
|
throw;
|
|
}
|
|
lk.lock();
|
|
finish_locked(from_completion);
|
|
}
|
|
|
|
void finish_locked(bool from_completion) noexcept
|
|
{
|
|
if (from_completion) {
|
|
--running_completion_;
|
|
} else {
|
|
--running_normal_;
|
|
}
|
|
if (phase_ == Phase::joining) {
|
|
state_cv_.notify_all();
|
|
}
|
|
}
|
|
|
|
void worker_loop()
|
|
{
|
|
std::unique_lock lk{mu_};
|
|
for (;;) {
|
|
work_cv_.wait(lk, [this] {
|
|
if (abort_start_ || inline_mode_) {
|
|
return true;
|
|
}
|
|
if (phase_ != Phase::running && phase_ != Phase::joining) {
|
|
return false;
|
|
}
|
|
return !completion_.empty() || !normal_.empty();
|
|
});
|
|
if (abort_start_ || inline_mode_) {
|
|
return;
|
|
}
|
|
const bool from_completion = !completion_.empty();
|
|
std::coroutine_handle<> handle;
|
|
if (from_completion) {
|
|
handle = completion_.front();
|
|
completion_.pop_front();
|
|
} else {
|
|
handle = normal_.front();
|
|
normal_.pop_front();
|
|
}
|
|
run_locked(lk, handle, from_completion);
|
|
}
|
|
}
|
|
|
|
ThreadExecutorOptions options_;
|
|
mutable std::mutex mu_{};
|
|
std::condition_variable work_cv_{}; // wakes workers
|
|
std::condition_variable state_cv_{}; // wakes start()/join() waiters
|
|
std::deque<std::coroutine_handle<>> normal_{};
|
|
std::deque<std::coroutine_handle<>> completion_{};
|
|
std::vector<std::thread> workers_{};
|
|
std::size_t running_normal_{0};
|
|
std::size_t running_completion_{0};
|
|
std::size_t reserved_{0};
|
|
std::uint64_t rejected_{0};
|
|
std::uint64_t legacy_posts_{0};
|
|
std::uint64_t inline_after_join_{0};
|
|
Phase phase_{Phase::created};
|
|
bool closed_{false};
|
|
bool inline_mode_{false};
|
|
bool abort_start_{false};
|
|
};
|
|
|
|
} // namespace Void::Async
|