feat(async): add ThreadExecutor, FuturePool, AsyncChannel, bounded parallel_for, and spawn fix (M-ASYNC-04)

This commit is contained in:
faumaray committed 2026-12-01 10:15:03 +03:00
1 parent 5c24f8e84f
commit b2c84114fe
9 files changed
+4763 -8

No files matched your search

+768
View File
@@ -0,0 +1,768 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Async/Timer.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <coroutine>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <expected>
#include <list>
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <string>
#include <type_traits>
#include <utility>
// ── AsyncChannel ──────────────────────────────────────────────────────────────
// A bounded multi-producer / multi-consumer channel with coroutine `send` /
// `receive`, cooperative cancellation and optional injected-clock deadlines
// (C-03/C-04). Blocking waits do not exist: a waiter suspends its coroutine
// and is always resumed through `resume.post_completion(...)` (never while the
// channel lock is held; an executor that has been joined resumes the handle
// inline on the calling thread, as ThreadExecutor does after join()).
//
// Arbitration (one `std::mutex` covers the buffer and both waiter lists)
// A waiter is a heap node (`shared_ptr`) with the state
// {fresh, linked, claimed, cancelled, timed_out, closed, overloaded}.
// `fresh` is the pre-link state (callbacks that settle a fresh waiter make
// the awaiting coroutine skip suspension); `overloaded` is the internal
// result of a refused wait. Pairing a sender with a receiver happens in ONE
// critical section: the waiter is unlinked and claimed and the value is
// moved, so a value is always in exactly one place: the sender's node, the
// buffer, or the receiver's slot. Stop callbacks and timer callbacks take the
// same lock: a still-`linked` waiter is unlinked and settled
// `cancelled`/`timed_out` (a sender keeps its value and gets it back), a
// `claimed` waiter is left alone (a sender succeeded, a receiver already
// holds its value). Each operation is settled exactly once.
//
// Ordering and capacity
// FIFO means per-producer order (items of one producer are received in the
// order they were sent; items of different producers interleave). Waiting
// senders and waiting receivers are served in arrival order. `capacity` and
// `max_waiters` (per direction) must be > 0 (`create` -> invalid_argument).
// A wait that would exceed `max_waiters` returns `overloaded` (a send gets
// its value back).
//
// Close
// `close()` is idempotent and noexcept. Waiting senders complete `closed`
// and get their value back; waiting receivers complete `closed`. Items
// already buffered stay receivable: receivers drain the buffer in FIFO order
// and then get `closed`. `send`/`try_send` on a closed channel return
// `closed` with the value.
//
// Options checks (send/receive with OperationOptions), in this order and
// BEFORE any state change (a send returns its value in `SendFailure`):
// 1. stop already requested -> cancelled
// 2. a deadline is set: it is judged by
// `timers->clock()`; already reached -> timed_out
// no `timers` configured -> invalid_argument
// 3. the fast path (value moved / received)
// 4. a deadline timer is armed (schedule_at failure: overloaded ->
// overloaded, stopped -> cancelled; the value is returned)
// 5. the waiter is linked and the coroutine suspends.
// `TimerEvent::closed` (queue closed or destroyed) settles the wait
// `cancelled`. The system clock is never consulted.
//
// Lifetime and caller errors
// * `send`/`receive` return lazy Tasks; their frames hold
// `shared_from_this()`, so the channel outlives every pending operation.
// * Destroying a Task that is suspended inside a channel operation is a
// caller error (the waiter would be resumed into a destroyed frame).
// * The resume executor and the TimerQueue must outlive the channel and every
// pending operation.
// * Timer callbacks hold only weak references (channel + waiter); a stop or
// timer callback that races with completion finds a settled waiter and
// does nothing. No raw pointer into a coroutine frame is ever captured.
// * A `std::stop_callback` is never constructed or destroyed while the
// channel lock is held, and a timer is never cancelled under the lock.
// * Exceptions: if `T`'s move constructor throws, the exception propagates
// from the operation; the channel's structural invariants (lists, bound)
// are preserved, but the value being moved is then unspecified (strong
// guarantee only for T with a non-throwing move constructor).
namespace Void::Async
{
enum class ChannelError : std::uint8_t {
closed,
empty,
full,
cancelled,
timed_out,
overloaded,
invalid_argument
};
// closed -> AsyncErrorCode::closed, cancelled -> cancelled, timed_out ->
// timeout, overloaded/full -> overloaded, empty/invalid_argument ->
// invalid_argument.
[[nodiscard]] inline Void::Result::Error
make_async_error(ChannelError error, std::string message = {})
{
AsyncErrorCode code = AsyncErrorCode::invalid_argument;
const char* text = "Invalid async channel argument";
switch (error) {
case ChannelError::closed:
code = AsyncErrorCode::closed;
text = "Async channel is closed";
break;
case ChannelError::empty:
code = AsyncErrorCode::invalid_argument;
text = "Async channel is empty";
break;
case ChannelError::full:
code = AsyncErrorCode::overloaded;
text = "Async channel is full";
break;
case ChannelError::cancelled:
code = AsyncErrorCode::cancelled;
text = "Async channel operation cancelled";
break;
case ChannelError::timed_out:
code = AsyncErrorCode::timeout;
text = "Async channel operation deadline expired";
break;
case ChannelError::overloaded:
code = AsyncErrorCode::overloaded;
text = "Async channel waiter capacity exceeded";
break;
case ChannelError::invalid_argument:
code = AsyncErrorCode::invalid_argument;
text = "Invalid async channel argument";
break;
}
if (message.empty()) {
message = text;
}
return make_async_error(code, std::move(message));
}
struct ChannelOptions {
std::size_t capacity{1024};
std::size_t max_waiters{1024};
// Required only for waits with a deadline; must outlive the channel.
TimerQueue* timers{nullptr};
};
template <class T>
struct SendFailure {
ChannelError error;
T value;
};
namespace detail
{
enum class ChannelWaiterState : std::uint8_t {
fresh,
linked,
claimed,
cancelled,
timed_out,
closed,
overloaded
};
// Heap-allocated so stop/timer callbacks can reference it through shared or
// weak ownership instead of a pointer into a coroutine frame. All members
// except `sender` are protected by the owning channel's mutex (the waiter's
// owner may read `value` without the lock only after the state is terminal).
template <class T>
struct ChannelWaiter {
explicit ChannelWaiter(bool is_sender) noexcept : sender(is_sender) {}
const bool sender;
ChannelWaiterState state{ChannelWaiterState::fresh};
// Sender: the value to deliver. Receiver: the delivered value.
std::optional<T> value{};
std::coroutine_handle<> handle{};
TimerHandle timer{};
typename std::list<std::shared_ptr<ChannelWaiter>>::iterator position{};
};
} // namespace detail
template <class T>
class AsyncChannel : public std::enable_shared_from_this<AsyncChannel<T>>
{
static_assert(std::is_object_v<T> && std::is_move_constructible_v<T>,
"AsyncChannel<T> requires a move-constructible object type");
using Waiter = detail::ChannelWaiter<T>;
using WaiterPtr = std::shared_ptr<Waiter>;
using WaiterList = std::list<WaiterPtr>;
using WaiterState = detail::ChannelWaiterState;
using SendResult = std::expected<void, SendFailure<T>>;
using ReceiveResult = std::expected<T, ChannelError>;
public:
// Errors: invalid_argument when capacity == 0 or max_waiters == 0.
[[nodiscard]] static Void::Result::Result<std::shared_ptr<AsyncChannel>>
create(Executor& resume, ChannelOptions options = {})
{
if (options.capacity == 0) {
return std::unexpected{make_async_error(
AsyncErrorCode::invalid_argument,
"AsyncChannel capacity must be greater than zero")};
}
if (options.max_waiters == 0) {
return std::unexpected{make_async_error(
AsyncErrorCode::invalid_argument,
"AsyncChannel max_waiters must be greater than zero")};
}
return std::shared_ptr<AsyncChannel>(new AsyncChannel(resume, options));
}
AsyncChannel(const AsyncChannel&) = delete;
AsyncChannel& operator=(const AsyncChannel&) = delete;
AsyncChannel(AsyncChannel&&) = delete;
AsyncChannel& operator=(AsyncChannel&&) = delete;
~AsyncChannel() = default;
// Non-blocking send. Errors (the value is returned): closed, full.
[[nodiscard]] std::expected<void, SendFailure<T>> try_send(T value)
{
WaiterPtr woken;
SendAttempt attempt{};
{
std::lock_guard lk{mu_};
attempt = try_send_locked(value, woken);
}
resume_waiter(woken);
switch (attempt) {
case SendAttempt::sent:
return {};
case SendAttempt::closed:
return std::unexpected{SendFailure<T>{ChannelError::closed, std::move(value)}};
case SendAttempt::full:
break;
}
return std::unexpected{SendFailure<T>{ChannelError::full, std::move(value)}};
}
// Suspends until the value is delivered (to a waiting receiver or the
// buffer). Results: success; or SendFailure with the value returned:
// closed, cancelled, timed_out, overloaded, invalid_argument (see the
// header comment for the check order).
[[nodiscard]] Coro::Task<std::expected<void, SendFailure<T>>>
send(T value, OperationOptions options = {})
{
return send_impl(this->shared_from_this(), std::move(value), std::move(options));
}
// Non-blocking receive. Errors: empty, closed (closed AND drained).
[[nodiscard]] std::expected<T, ChannelError> try_receive()
{
std::optional<T> out;
WaiterPtr woken;
ReceiveAttempt attempt{};
{
std::lock_guard lk{mu_};
attempt = try_receive_locked(out, woken);
}
resume_waiter(woken);
switch (attempt) {
case ReceiveAttempt::received:
return std::move(*out);
case ReceiveAttempt::closed:
return std::unexpected{ChannelError::closed};
case ReceiveAttempt::empty:
break;
}
return std::unexpected{ChannelError::empty};
}
// Suspends until a value arrives. Errors: closed (closed AND drained),
// cancelled, timed_out, overloaded, invalid_argument.
[[nodiscard]] Coro::Task<std::expected<T, ChannelError>>
receive(OperationOptions options = {})
{
return receive_impl(this->shared_from_this(), std::move(options));
}
// Idempotent. See the header comment.
void close() noexcept
{
WaiterList senders;
WaiterList receivers;
{
std::lock_guard lk{mu_};
if (closed_) {
return;
}
closed_ = true;
senders.splice(senders.end(), senders_);
receivers.splice(receivers.end(), receivers_);
for (auto& waiter : senders) {
waiter->state = WaiterState::closed;
}
for (auto& waiter : receivers) {
waiter->state = WaiterState::closed;
}
}
for (auto& waiter : senders) {
resume_waiter(waiter);
}
for (auto& waiter : receivers) {
resume_waiter(waiter);
}
}
// Number of buffered items.
[[nodiscard]] std::size_t size() const
{
std::lock_guard lk{mu_};
return buffer_.size();
}
[[nodiscard]] bool is_closed() const
{
std::lock_guard lk{mu_};
return closed_;
}
private:
enum class SendAttempt : std::uint8_t { sent, closed, full };
enum class ReceiveAttempt : std::uint8_t { received, closed, empty };
AsyncChannel(Executor& resume, const ChannelOptions& options)
: resume_(resume)
, capacity_(options.capacity)
, max_waiters_(options.max_waiters)
, timers_(options.timers)
{
}
// ── locked primitives (mu_ held) ──────────────────────────────────────
// Moves from `value` only on success. A waiting receiver implies an empty
// buffer, so a direct hand-off preserves FIFO order.
[[nodiscard]] SendAttempt try_send_locked(T& value, WaiterPtr& woken)
{
if (closed_) {
return SendAttempt::closed;
}
if (!receivers_.empty()) {
WaiterPtr receiver = receivers_.front();
receiver->value.emplace(std::move(value));
receivers_.pop_front();
receiver->state = WaiterState::claimed;
woken = std::move(receiver);
return SendAttempt::sent;
}
if (buffer_.size() < capacity_) {
buffer_.push_back(std::move(value));
return SendAttempt::sent;
}
return SendAttempt::full;
}
// A waiting sender implies a full buffer: the freed slot is refilled from
// the first waiting sender, which is claimed (it succeeded).
[[nodiscard]] ReceiveAttempt try_receive_locked(std::optional<T>& out, WaiterPtr& woken)
{
if (!buffer_.empty()) {
out.emplace(std::move(buffer_.front()));
buffer_.pop_front();
if (!senders_.empty()) {
WaiterPtr sender = senders_.front();
try {
buffer_.push_back(std::move(*sender->value));
} catch (...) {
// Best effort: put the received value back so it is not lost.
try {
buffer_.push_front(std::move(*out));
} catch (...) {
}
throw;
}
senders_.pop_front();
sender->state = WaiterState::claimed;
woken = std::move(sender);
}
return ReceiveAttempt::received;
}
if (closed_) {
return ReceiveAttempt::closed;
}
return ReceiveAttempt::empty;
}
void link_locked(WaiterList& list, const WaiterPtr& waiter)
{
waiter->position = list.insert(list.end(), waiter);
waiter->state = WaiterState::linked;
}
// ── settlement (no lock held) ─────────────────────────────────────────
// Cancels the waiter's deadline timer and resumes its coroutine through
// the completion lane. The waiter must already be in a terminal state.
void resume_waiter(WaiterPtr& waiter)
{
if (!waiter) {
return;
}
(void)waiter->timer.cancel();
resume_.post_completion(waiter->handle);
waiter.reset();
}
// Stop/timer callback entry point. A `fresh` waiter is only marked (the
// awaiting coroutine will not suspend); a `linked` waiter is unlinked and
// resumed; anything else was already settled and is left alone.
void settle_pending(const WaiterPtr& waiter, WaiterState to) noexcept
{
{
std::lock_guard lk{mu_};
if (waiter->state == WaiterState::fresh) {
waiter->state = to;
return;
}
if (waiter->state != WaiterState::linked) {
return;
}
(waiter->sender ? senders_ : receivers_).erase(waiter->position);
waiter->state = to;
}
WaiterPtr settled = waiter;
resume_waiter(settled);
}
// ── option handling ───────────────────────────────────────────────────
[[nodiscard]] std::optional<ChannelError> precheck(const OperationOptions& options) const
{
if (options.stop.stop_requested()) {
return ChannelError::cancelled;
}
if (options.deadline.has_value()) {
if (timers_ == nullptr) {
return ChannelError::invalid_argument;
}
if (timers_->clock().now() >= *options.deadline) {
return ChannelError::timed_out;
}
}
return std::nullopt;
}
// Arms the deadline timer while the waiter is still `fresh` (so a failure
// leaves no state behind and a timer that fires early settles the fresh
// waiter without a ticket). The callback holds only weak references.
[[nodiscard]] std::optional<ChannelError>
arm_deadline(const WaiterPtr& waiter, Void::Time::MonotonicClock::time_point deadline)
{
auto scheduled = timers_->schedule_at(
deadline,
TimerCallback{[channel = this->weak_from_this(),
target = std::weak_ptr<Waiter>{waiter}](TimerEvent event) noexcept {
const auto chan = channel.lock();
const auto settled = target.lock();
if (chan && settled) {
chan->settle_pending(
settled,
event == TimerEvent::expired ? WaiterState::timed_out
: WaiterState::cancelled);
}
}});
if (!scheduled.has_value()) {
switch (scheduled.error()) {
case AdmissionError::overloaded:
return ChannelError::overloaded;
case AdmissionError::stopped:
return ChannelError::cancelled;
case AdmissionError::deadline_expired:
return ChannelError::timed_out;
case AdmissionError::invalid_argument:
case AdmissionError::self_join:
return ChannelError::invalid_argument;
}
return ChannelError::invalid_argument;
}
bool settled_meanwhile = false;
{
std::lock_guard lk{mu_};
if (waiter->state == WaiterState::fresh) {
waiter->timer = std::move(*scheduled);
} else {
settled_meanwhile = true;
}
}
if (settled_meanwhile) {
(void)scheduled->cancel();
}
return std::nullopt;
}
struct StopFn {
std::weak_ptr<AsyncChannel> channel;
WaiterPtr waiter;
void operator()() const noexcept
{
// Copy first: once the waiter is settled the resumed frame may
// destroy the stop_callback that owns this object.
const auto chan = channel.lock();
const WaiterPtr target = waiter;
if (chan) {
chan->settle_pending(target, WaiterState::cancelled);
}
}
};
// ── awaiters ──────────────────────────────────────────────────────────
// Links the waiter (re-running the fast path under the same lock so no
// wake-up can be lost) and suspends. Once the waiter is visible to other
// threads the frame may be resumed and destroyed concurrently, so
// everything after the unlock touches locals only.
struct SendAwaiter {
std::shared_ptr<AsyncChannel> channel;
WaiterPtr waiter;
[[nodiscard]] bool await_ready() const noexcept { return false; }
[[nodiscard]] bool await_suspend(std::coroutine_handle<> handle)
{
std::shared_ptr<AsyncChannel> chan = channel;
WaiterPtr self = waiter;
WaiterPtr woken;
bool suspended = false;
try {
std::lock_guard lk{chan->mu_};
if (self->state == WaiterState::fresh) {
switch (chan->try_send_locked(*self->value, woken)) {
case SendAttempt::sent:
self->state = WaiterState::claimed;
break;
case SendAttempt::closed:
self->state = WaiterState::closed;
break;
case SendAttempt::full:
if (chan->senders_.size() >= chan->max_waiters_) {
self->state = WaiterState::overloaded;
} else {
self->handle = handle;
chan->link_locked(chan->senders_, self);
suspended = true;
}
break;
}
}
} catch (...) {
(void)self->timer.cancel();
throw;
}
if (suspended) {
return true;
}
(void)self->timer.cancel();
chan->resume_waiter(woken);
return false;
}
[[nodiscard]] SendResult await_resume()
{
WaiterState state{};
{
std::lock_guard lk{channel->mu_};
state = waiter->state;
}
switch (state) {
case WaiterState::claimed:
return {};
case WaiterState::closed:
return fail(ChannelError::closed);
case WaiterState::timed_out:
return fail(ChannelError::timed_out);
case WaiterState::overloaded:
return fail(ChannelError::overloaded);
case WaiterState::cancelled:
case WaiterState::fresh:
case WaiterState::linked:
break;
}
return fail(ChannelError::cancelled);
}
private:
[[nodiscard]] SendResult fail(ChannelError error)
{
return std::unexpected{SendFailure<T>{error, std::move(*waiter->value)}};
}
};
struct ReceiveAwaiter {
std::shared_ptr<AsyncChannel> channel;
WaiterPtr waiter;
[[nodiscard]] bool await_ready() const noexcept { return false; }
[[nodiscard]] bool await_suspend(std::coroutine_handle<> handle)
{
std::shared_ptr<AsyncChannel> chan = channel;
WaiterPtr self = waiter;
WaiterPtr woken;
bool suspended = false;
try {
std::lock_guard lk{chan->mu_};
if (self->state == WaiterState::fresh) {
switch (chan->try_receive_locked(self->value, woken)) {
case ReceiveAttempt::received:
self->state = WaiterState::claimed;
break;
case ReceiveAttempt::closed:
self->state = WaiterState::closed;
break;
case ReceiveAttempt::empty:
if (chan->receivers_.size() >= chan->max_waiters_) {
self->state = WaiterState::overloaded;
} else {
self->handle = handle;
chan->link_locked(chan->receivers_, self);
suspended = true;
}
break;
}
}
} catch (...) {
(void)self->timer.cancel();
throw;
}
if (suspended) {
return true;
}
(void)self->timer.cancel();
chan->resume_waiter(woken);
return false;
}
[[nodiscard]] ReceiveResult await_resume()
{
WaiterState state{};
{
std::lock_guard lk{channel->mu_};
state = waiter->state;
}
switch (state) {
case WaiterState::claimed:
return std::move(*waiter->value);
case WaiterState::closed:
return std::unexpected{ChannelError::closed};
case WaiterState::timed_out:
return std::unexpected{ChannelError::timed_out};
case WaiterState::overloaded:
return std::unexpected{ChannelError::overloaded};
case WaiterState::cancelled:
case WaiterState::fresh:
case WaiterState::linked:
break;
}
return std::unexpected{ChannelError::cancelled};
}
};
// ── operations (free-standing coroutines holding the channel) ─────────
static Coro::Task<SendResult>
send_impl(std::shared_ptr<AsyncChannel> self, T value, OperationOptions options)
{
if (const auto refused = self->precheck(options); refused.has_value()) {
co_return std::unexpected{SendFailure<T>{*refused, std::move(value)}};
}
{
WaiterPtr woken;
SendAttempt attempt{};
{
std::lock_guard lk{self->mu_};
attempt = self->try_send_locked(value, woken);
}
self->resume_waiter(woken);
if (attempt == SendAttempt::sent) {
co_return SendResult{};
}
if (attempt == SendAttempt::closed) {
co_return std::unexpected{SendFailure<T>{ChannelError::closed, std::move(value)}};
}
}
auto waiter = std::make_shared<Waiter>(true);
waiter->value.emplace(std::move(value));
std::optional<std::stop_callback<StopFn>> stop_cb;
if (options.stop.stop_possible()) {
stop_cb.emplace(options.stop, StopFn{self->weak_from_this(), waiter});
}
if (options.deadline.has_value()) {
if (const auto failure = self->arm_deadline(waiter, *options.deadline);
failure.has_value()) {
co_return std::unexpected{SendFailure<T>{*failure, std::move(*waiter->value)}};
}
}
SendResult result = co_await SendAwaiter{self, waiter};
// Waits for a stop callback that is mid-settle (no lock is held here).
stop_cb.reset();
co_return result;
}
static Coro::Task<ReceiveResult>
receive_impl(std::shared_ptr<AsyncChannel> self, OperationOptions options)
{
if (const auto refused = self->precheck(options); refused.has_value()) {
co_return std::unexpected{*refused};
}
{
std::optional<T> out;
WaiterPtr woken;
ReceiveAttempt attempt{};
{
std::lock_guard lk{self->mu_};
attempt = self->try_receive_locked(out, woken);
}
self->resume_waiter(woken);
if (attempt == ReceiveAttempt::received) {
co_return ReceiveResult{std::move(*out)};
}
if (attempt == ReceiveAttempt::closed) {
co_return std::unexpected{ChannelError::closed};
}
}
auto waiter = std::make_shared<Waiter>(false);
std::optional<std::stop_callback<StopFn>> stop_cb;
if (options.stop.stop_possible()) {
stop_cb.emplace(options.stop, StopFn{self->weak_from_this(), waiter});
}
if (options.deadline.has_value()) {
if (const auto failure = self->arm_deadline(waiter, *options.deadline);
failure.has_value()) {
co_return std::unexpected{*failure};
}
}
ReceiveResult result = co_await ReceiveAwaiter{self, waiter};
stop_cb.reset();
co_return result;
}
Executor& resume_;
const std::size_t capacity_;
const std::size_t max_waiters_;
TimerQueue* const timers_;
mutable std::mutex mu_{};
std::deque<T> buffer_{};
WaiterList senders_{};
WaiterList receivers_{};
bool closed_{false};
};
} // namespace Void::Async
+17 -5
View File
@@ -276,29 +276,41 @@ struct ScheduleAwaiter {
// 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 {}; }
std::suspend_never initial_suspend() noexcept { return {}; }
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(Executor& executor, Coro::Task<void> task)
inline DetachedTask spawn_impl(Coro::Task<void> task)
{
co_await schedule_on(executor);
co_await std::move(task);
}
} // namespace Detail
inline void spawn(Executor& executor, Coro::Task<void> task)
{
Detail::spawn_impl(executor, std::move(task));
Detail::DetachedTask detached = Detail::spawn_impl(std::move(task));
executor.post(detached.handle);
}
struct ScheduleStatusAwaiter {
+131
View File
@@ -0,0 +1,131 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#include <concepts>
#include <coroutine>
#include <exception>
#include <expected>
#include <future>
#include <type_traits>
#include <utility>
// ── FuturePool ────────────────────────────────────────────────────────────────
// `std::future` adapter over a started `ThreadExecutor`.
//
// try_submit(f) is reserve-then-transfer:
// 1. one slot of the executor bound is reserved (`overloaded` / `stopped`
// are returned WITHOUT touching `f`: a rejected callable is never moved);
// 2. only after the reservation succeeded is `f` moved into a
// `std::packaged_task` owned by a self-destroying coroutine frame;
// 3. the frame is committed to the executor's normal lane.
// The reservation is released if any step throws (the exception propagates).
// Exceptions thrown by `f` are stored in the returned future. The executor
// bound counts queued, running and reserved work, so a running submission
// keeps its slot until `f` has returned.
//
// The executor must outlive the pool and must be started (or joined by the
// owner afterwards): a submission is resumed by a worker, or inline once the
// executor has been joined.
namespace Void::Async
{
namespace detail
{
// Fire-and-forget coroutine frame: created suspended, destroyed after it ran.
struct FutureJob {
struct promise_type {
FutureJob get_return_object() noexcept
{
return FutureJob{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 {}
// packaged_task stores the callable's exception in the future, so
// nothing escapes the frame.
void unhandled_exception() noexcept { std::terminate(); }
};
std::coroutine_handle<promise_type> handle{};
};
template <class R>
FutureJob run_future_job(std::packaged_task<R()> task)
{
task();
co_return;
}
// Releases a reservation unless dismissed.
class ReservationGuard
{
public:
explicit ReservationGuard(ThreadExecutor& executor) noexcept
: executor_(&executor)
{
}
ReservationGuard(const ReservationGuard&) = delete;
ReservationGuard& operator=(const ReservationGuard&) = delete;
~ReservationGuard()
{
if (executor_ != nullptr) {
executor_->release_reserved();
}
}
void dismiss() noexcept { executor_ = nullptr; }
private:
ThreadExecutor* executor_;
};
} // namespace detail
class FuturePool
{
public:
explicit FuturePool(ThreadExecutor& executor) noexcept
: executor_(&executor)
{
}
// Errors: overloaded (admitted() >= max_admitted), stopped (executor
// closed). On an error `f` is untouched. Throws only on allocation
// failure (the reservation is released first).
template <std::invocable F>
[[nodiscard]] std::expected<std::future<std::invoke_result_t<F>>, AdmissionError>
try_submit(F&& f)
{
using R = std::invoke_result_t<F>;
if (auto reserved = executor_->try_reserve_slot(); !reserved.has_value()) {
return std::unexpected{reserved.error()};
}
detail::ReservationGuard guard{*executor_};
std::packaged_task<R()> task{std::forward<F>(f)};
std::future<R> future = task.get_future();
detail::FutureJob job = detail::run_future_job<R>(std::move(task));
try {
executor_->commit_reserved(job.handle);
} catch (...) {
// The reservation is still held (guard releases it); the frame was
// never queued.
job.handle.destroy();
throw;
}
guard.dismiss();
return future;
}
private:
ThreadExecutor* executor_;
};
} // namespace Void::Async
+302 -3
View File
@@ -1,7 +1,20 @@
#pragma once
#include <Void/Async/ThreadPool.hpp>
#include <algorithm>
#include <atomic>
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <expected>
#include <future>
#include <limits>
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <type_traits>
#include <utility>
#include <vector>
namespace Void::Concurrency
@@ -9,6 +22,10 @@ namespace Void::Concurrency
// Submit one task per index in [first, last) to pool; block until all done.
// Exceptions from tasks propagate via std::future::get() to the caller.
//
// Every submitted future is waited for before the first exception is
// rethrown (a throwing task, or a failing submit, never leaves other tasks
// running against the caller's stack).
template <std::integral I, std::invocable<I> F>
void parallel_for(I first, I last, F&& f, ThreadPool& pool)
{
@@ -17,11 +34,25 @@ namespace Void::Concurrency
}
std::vector<std::future<void>> futures;
futures.reserve(static_cast<std::size_t>(last - first));
for (auto i = first; i < last; ++i) {
futures.push_back(pool.submit([f, i] { f(i); }));
std::exception_ptr first_error;
try {
for (auto i = first; i < last; ++i) {
futures.push_back(pool.submit([f, i] { f(i); }));
}
} catch (...) {
first_error = std::current_exception();
}
for (auto& fut : futures) {
fut.get();
try {
fut.get();
} catch (...) {
if (!first_error) {
first_error = std::current_exception();
}
}
}
if (first_error) {
std::rethrow_exception(first_error);
}
}
@@ -34,4 +65,272 @@ namespace Void::Concurrency
parallel_for(first, last, std::forward<F>(f), pool);
}
// ── Bounded, chunked parallel_for ────────────────────────────────────────
struct ParallelForOptions {
// Indices per chunk; zero is invalid.
std::size_t grain{1};
// Maximum chunks running at once (the calling thread counts when it
// runs chunks inline); zero means the pool's thread count.
std::size_t max_concurrency{0};
// No new chunk starts once stop is requested.
std::stop_token stop{};
// No new chunk starts after the first failed chunk. When false every
// chunk runs and all failures are counted.
bool stop_on_error{true};
};
struct ParallelForError {
enum class Kind : std::uint8_t {
invalid_argument,
rejected, // reserved: not produced in this release
stopped,
failed
} kind;
std::size_t chunks_total{0};
std::size_t chunks_started{0};
std::size_t chunks_failed{0};
std::optional<std::size_t> first_failed_chunk{};
std::exception_ptr first_exception{};
};
namespace detail
{
// Shared between the caller and every runner. Runners hold it through
// a shared_ptr, so a runner that starts after the caller stopped
// claiming chunks (or that the pool never started in time) never
// touches freed state.
template <class Fn, class Index> struct PForState {
template <class G>
PForState(G&& fn_in, Index first_in, std::uintmax_t count_in,
std::uintmax_t grain_in, std::size_t chunks,
std::stop_token stop_in, bool stop_on_error_in)
: fn(std::forward<G>(fn_in)), first(first_in),
count(count_in), grain(grain_in), chunks_total(chunks),
stop(std::move(stop_in)), stop_on_error(stop_on_error_in)
{
}
const Fn fn;
const Index first;
const std::uintmax_t count;
const std::uintmax_t grain;
const std::size_t chunks_total;
const std::stop_token stop;
const bool stop_on_error;
std::atomic<std::size_t> next_chunk{0};
std::atomic<std::size_t> started{0};
std::atomic<bool> failed_flag{false};
std::atomic<bool> aborted{false};
std::mutex error_mu{};
std::size_t failed{0};
std::optional<std::size_t> first_failed{};
std::exception_ptr first_exception{};
[[nodiscard]] bool should_stop() const noexcept
{
return aborted.load(std::memory_order_acquire) ||
stop.stop_requested() ||
(stop_on_error &&
failed_flag.load(std::memory_order_acquire));
}
void record_failure(std::size_t chunk, std::exception_ptr error)
{
std::lock_guard lk{error_mu};
++failed;
if (!first_failed.has_value() || chunk < *first_failed) {
first_failed = chunk;
first_exception = std::move(error);
}
failed_flag.store(true, std::memory_order_release);
}
// Claims and runs chunks until the range is exhausted, a stop
// is requested or (stop_on_error) a chunk failed. Never throws:
// every chunk failure is recorded.
void run_chunks() noexcept
{
using U = std::make_unsigned_t<std::conditional_t<
std::same_as<Index, bool>, unsigned char, Index>>;
for (;;) {
if (should_stop()) {
return;
}
const std::size_t chunk =
next_chunk.fetch_add(1, std::memory_order_acq_rel);
if (chunk >= chunks_total) {
return;
}
// A stop that arrived between the check and the claim:
// the claimed chunk is abandoned unstarted.
if (should_stop()) {
return;
}
started.fetch_add(1, std::memory_order_relaxed);
const std::uintmax_t begin =
static_cast<std::uintmax_t>(chunk) * grain;
const std::uintmax_t length =
std::min<std::uintmax_t>(grain, count - begin);
try {
for (std::uintmax_t k = 0; k < length; ++k) {
const Index i = static_cast<Index>(
static_cast<U>(static_cast<U>(first) +
static_cast<U>(begin + k)));
fn(i);
}
} catch (...) {
record_failure(chunk, std::current_exception());
}
}
}
};
// Waits for every future on every exit path (including an exception
// thrown while submitting): a runner may still call `f`, which can
// capture the caller's stack by reference.
class RunnerJoin
{
public:
explicit RunnerJoin(std::vector<std::future<void>>& futures)
: futures_(futures)
{
}
RunnerJoin(const RunnerJoin&) = delete;
RunnerJoin& operator=(const RunnerJoin&) = delete;
~RunnerJoin() { join(); }
void join() noexcept
{
for (auto& fut : futures_) {
if (fut.valid()) {
fut.wait();
}
}
}
private:
std::vector<std::future<void>>& futures_;
};
} // namespace detail
// Bounded, chunked parallel_for over [first, last).
//
// The range is split into chunks of `options.grain` indices. At most
// `max_concurrency` chunks run at once (0 = pool.thread_count(); the
// caller counts when it runs chunks inline). Runners are submitted with
// try_submit; when the pool rejects a runner (full or stopped) the CALLING
// thread runs chunks itself (no further runner is submitted). The caller
// waits for EVERY submitted runner, including runners that never started.
//
// Results: success when every chunk ran (also for first >= last);
// otherwise a ParallelForError with precedence invalid_argument (grain ==
// 0) > failed (a chunk threw; the lowest-indexed failed chunk is
// reported) > stopped (stop requested before every chunk started).
// `Kind::rejected` is not produced in this release. With `stop_on_error`
// no new chunk starts after the first failure (chunks already running
// finish). Chunk boundaries and the range arithmetic use the unsigned type
// of `I`, so the full range of `I` is safe.
//
// `f` is copied once into shared state and invoked concurrently through a
// const reference, so it must be safe to call concurrently (as with the
// legacy overload). Calling this from a worker of the same `pool` is
// unsupported (the caller would wait for runners that need its thread).
template <std::integral I, std::invocable<I> F>
[[nodiscard]] std::expected<void, ParallelForError>
parallel_for(I first, I last, F&& f, ThreadPool& pool,
ParallelForOptions options)
{
using Fn = std::decay_t<F>;
using U = std::make_unsigned_t<
std::conditional_t<std::same_as<I, bool>, unsigned char, I>>;
if (options.grain == 0) {
return std::unexpected{ParallelForError{
ParallelForError::Kind::invalid_argument}};
}
if (first >= last) {
return {};
}
const std::uintmax_t count = static_cast<std::uintmax_t>(
static_cast<U>(static_cast<U>(last) - static_cast<U>(first)));
const std::uintmax_t grain = options.grain;
const std::uintmax_t chunk_count =
count / grain + (count % grain != 0 ? 1 : 0);
if (chunk_count > std::numeric_limits<std::size_t>::max()) {
return std::unexpected{ParallelForError{
ParallelForError::Kind::invalid_argument}};
}
const std::size_t chunks_total = static_cast<std::size_t>(chunk_count);
std::size_t concurrency = options.max_concurrency != 0
? options.max_concurrency
: pool.thread_count();
concurrency = std::max<std::size_t>(concurrency, 1);
const std::size_t runner_count = std::min(concurrency, chunks_total);
auto state = std::make_shared<detail::PForState<Fn, I>>(
std::forward<F>(f), first, count, grain, chunks_total, options.stop,
options.stop_on_error);
std::vector<std::future<void>> futures;
futures.reserve(runner_count);
bool run_inline = false;
if (!options.stop.stop_requested()) {
// Declared after `futures`: waits for every submitted runner on
// every exit path, including an exception while submitting.
detail::RunnerJoin join{futures};
try {
for (std::size_t r = 0; r < runner_count; ++r) {
// The runner moves its reference out of the capture and
// drops it before its future becomes ready, so the caller
// always releases the last reference: the shared state
// (copied F, stored exception) is never destroyed on a
// pool worker after parallel_for has returned.
auto submitted = pool.try_submit(
[runner_state = state]() mutable {
auto local = std::move(runner_state);
local->run_chunks();
});
if (!submitted.has_value()) {
run_inline = true;
break;
}
futures.push_back(std::move(*submitted));
}
if (run_inline) {
// The pool is full or stopped: this thread is one more
// runner (fewer than runner_count runners were submitted,
// so the total stays within the bound).
state->run_chunks();
}
} catch (...) {
state->aborted.store(true, std::memory_order_release);
throw;
}
}
const std::size_t started =
state->started.load(std::memory_order_acquire);
std::lock_guard lk{state->error_mu};
if (state->failed > 0) {
return std::unexpected{ParallelForError{
ParallelForError::Kind::failed, chunks_total, started,
state->failed, state->first_failed, state->first_exception}};
}
if (started < chunks_total) {
return std::unexpected{ParallelForError{
ParallelForError::Kind::stopped, chunks_total, started, 0,
std::nullopt, nullptr}};
}
return {};
}
} // namespace Void::Concurrency
+604
View File
@@ -0,0 +1,604 @@
#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
File diff suppressed because it is too large. Load diff
+245
View File
@@ -0,0 +1,245 @@
#include <Void/Async/FuturePool.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <future>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <string>
#include <thread>
#include <utility>
// All assertions run on the test thread; callables executed by workers only
// touch atomics (the assertion context is thread_local).
namespace
{
using namespace Void::Async;
using namespace std::chrono_literals;
class Gate
{
public:
void open()
{
{
std::lock_guard lk{mu_};
open_ = true;
}
cv_.notify_all();
}
void wait()
{
std::unique_lock lk{mu_};
cv_.wait(lk, [this] { return open_; });
}
private:
std::mutex mu_{};
std::condition_variable cv_{};
bool open_{false};
};
template <class Pred>
bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms)
{
const auto end = std::chrono::steady_clock::now() + timeout;
while (!pred()) {
if (std::chrono::steady_clock::now() >= end) {
return false;
}
std::this_thread::sleep_for(1ms);
}
return true;
}
// Opens the gate before the executor is destroyed, so a failed assertion can
// never leave a blocked callable hanging ~ThreadExecutor.
struct Fixture {
Gate gate{};
std::unique_ptr<ThreadExecutor> exec{};
Fixture(std::size_t workers, std::size_t max_admitted)
{
auto created = ThreadExecutor::create(
ThreadExecutorOptions{.workers = workers, .max_admitted = max_admitted});
Void::Testing::require(created.has_value());
exec = std::move(*created);
Void::Testing::require(exec->start().has_value());
}
~Fixture() { gate.open(); }
Fixture(const Fixture&) = delete;
Fixture& operator=(const Fixture&) = delete;
};
// Move-only callable that records every move: proves a rejected submission
// never consumed it.
struct TrackedCallable {
std::shared_ptr<std::atomic<int>> moves{std::make_shared<std::atomic<int>>(0)};
std::unique_ptr<int> payload{std::make_unique<int>(41)};
std::atomic<bool>* ran{nullptr};
TrackedCallable() = default;
explicit TrackedCallable(std::atomic<bool>* ran_flag) : ran(ran_flag) {}
TrackedCallable(TrackedCallable&& other) noexcept
: moves(other.moves)
, payload(std::move(other.payload))
, ran(other.ran)
{
moves->fetch_add(1);
}
TrackedCallable& operator=(TrackedCallable&&) = delete;
TrackedCallable(const TrackedCallable&) = delete;
TrackedCallable& operator=(const TrackedCallable&) = delete;
int operator()()
{
if (ran != nullptr) {
ran->store(true);
}
return payload ? *payload + 1 : -1;
}
};
} // namespace
Void::Testing::Test future_pool_overloaded_does_not_consume_callable()
{
std::atomic<bool> blocker_running{false};
std::atomic<bool> ran{false};
Fixture fx{1, 1};
FuturePool pool{*fx.exec};
auto blocker = pool.try_submit([&] {
blocker_running.store(true);
fx.gate.wait();
return 7;
});
Void::Testing::require(blocker.has_value());
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
TrackedCallable callable{&ran};
const auto rejected = pool.try_submit(std::move(callable));
Void::Testing::require(!rejected.has_value());
Void::Testing::expect(rejected.error() == AdmissionError::overloaded);
// Reserve-then-transfer: the callable was not even moved from.
Void::Testing::expect_eq(callable.moves->load(), 0);
Void::Testing::require(callable.payload != nullptr);
Void::Testing::expect_eq(*callable.payload, 41);
Void::Testing::expect(!ran.load());
fx.gate.open();
Void::Testing::expect_eq(blocker->get(), 7);
Void::Testing::require(wait_until([&] { return fx.exec->admitted() == 0; }));
// The very same callable is still usable.
auto accepted = pool.try_submit(std::move(callable));
Void::Testing::require(accepted.has_value());
Void::Testing::expect_eq(accepted->get(), 42);
Void::Testing::expect(ran.load());
}
Void::Testing::Test future_pool_stopped_after_close()
{
Fixture fx{1, 4};
FuturePool pool{*fx.exec};
auto before = pool.try_submit([] { return 1; });
Void::Testing::require(before.has_value());
Void::Testing::expect_eq(before->get(), 1);
fx.exec->close();
std::atomic<bool> ran{false};
TrackedCallable callable{&ran};
const auto stopped = pool.try_submit(std::move(callable));
Void::Testing::require(!stopped.has_value());
Void::Testing::expect(stopped.error() == AdmissionError::stopped);
Void::Testing::expect_eq(callable.moves->load(), 0);
Void::Testing::expect(callable.payload != nullptr);
Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{0});
Void::Testing::require(fx.exec->join().has_value());
Void::Testing::expect(!ran.load());
}
Void::Testing::Test future_pool_exception_in_future()
{
Fixture fx{2, 8};
FuturePool pool{*fx.exec};
auto failing = pool.try_submit([]() -> int { throw std::runtime_error{"boom"}; });
Void::Testing::require(failing.has_value());
bool caught = false;
try {
(void)failing->get();
} catch (const std::runtime_error& error) {
caught = std::string{error.what()} == "boom";
}
Void::Testing::expect(caught);
// void callables work, and a thrown exception does not poison the pool.
std::atomic<int> ran{0};
auto void_job = pool.try_submit([&ran] { ran.fetch_add(1); });
Void::Testing::require(void_job.has_value());
void_job->get();
Void::Testing::expect_eq(ran.load(), 1);
auto after = pool.try_submit([] { return 5; });
Void::Testing::require(after.has_value());
Void::Testing::expect_eq(after->get(), 5);
// Slots are released even when the callable threw.
Void::Testing::expect(wait_until([&] { return fx.exec->admitted() == 0; }));
}
Void::Testing::Test future_pool_bound_includes_running()
{
std::atomic<bool> first_running{false};
std::atomic<int> started{0};
Fixture fx{1, 2};
FuturePool pool{*fx.exec};
auto running = pool.try_submit([&] {
first_running.store(true);
started.fetch_add(1);
fx.gate.wait();
return 1;
});
Void::Testing::require(running.has_value());
Void::Testing::require(wait_until([&] { return first_running.load(); }));
// The running callable still counts against the bound.
Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{1});
auto queued = pool.try_submit([&] {
started.fetch_add(1);
return 2;
});
Void::Testing::require(queued.has_value());
Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{2});
const auto rejected = pool.try_submit([] { return 3; });
Void::Testing::require(!rejected.has_value());
Void::Testing::expect(rejected.error() == AdmissionError::overloaded);
Void::Testing::expect_eq(fx.exec->stats().rejected, std::uint64_t{1});
fx.gate.open();
Void::Testing::expect_eq(running->get(), 1);
Void::Testing::expect_eq(queued->get(), 2);
Void::Testing::expect_eq(started.load(), 2);
Void::Testing::require(wait_until([&] { return fx.exec->admitted() == 0; }));
auto again = pool.try_submit([] { return 4; });
Void::Testing::require(again.has_value());
Void::Testing::expect_eq(again->get(), 4);
}
@@ -0,0 +1,626 @@
#include <Void/Async/ParallelFor.hpp>
#include <Void/Async/ThreadPool.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <expected>
#include <limits>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <stop_token>
#include <string>
#include <thread>
#include <vector>
// Assertions run on the test thread only (the assertion context is
// thread_local); the loop bodies executed by pool workers only touch atomics or
// distinct array elements.
namespace
{
using namespace Void::Concurrency;
using namespace std::chrono_literals;
using Kind = ParallelForError::Kind;
class Gate
{
public:
void open()
{
{
std::lock_guard lk{mu_};
open_ = true;
}
cv_.notify_all();
}
void wait()
{
std::unique_lock lk{mu_};
cv_.wait(lk, [this] { return open_; });
}
private:
std::mutex mu_{};
std::condition_variable cv_{};
bool open_{false};
};
template <class Pred>
bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms)
{
const auto end = std::chrono::steady_clock::now() + timeout;
while (!pred()) {
if (std::chrono::steady_clock::now() >= end) {
return false;
}
std::this_thread::sleep_for(1ms);
}
return true;
}
// Tracks the maximum number of concurrently running loop bodies.
struct ConcurrencyMeter {
std::atomic<int> active{0};
std::atomic<int> peak{0};
void enter()
{
const int now = active.fetch_add(1) + 1;
int seen = peak.load();
while (now > seen && !peak.compare_exchange_weak(seen, now)) {
}
}
void leave() { active.fetch_sub(1); }
};
std::string what(const std::exception_ptr& error)
{
if (!error) {
return "<none>";
}
try {
std::rethrow_exception(error);
} catch (const std::exception& e) {
return e.what();
} catch (...) {
return "<non-std>";
}
}
// Opens the gate on destruction so a failed assertion cannot leave a blocked
// pool task hanging ~ThreadPool. Declare it AFTER the pool it protects.
struct GateGuard {
Gate& gate;
~GateGuard() { gate.open(); }
};
// Opens the gate and joins a helper thread on every exit path.
struct ThreadJoiner {
Gate& gate;
std::thread& thread;
~ThreadJoiner()
{
gate.open();
if (thread.joinable()) {
thread.join();
}
}
};
} // namespace
Void::Testing::Test parallel_for_bounded_grain_and_concurrency_limit()
{
constexpr int kCount = 40;
ThreadPool pool{4};
// grain = 3 over [0, 40): 14 chunks, at most 2 running at once.
{
ConcurrencyMeter meter;
std::vector<std::atomic<int>> hits(kCount);
std::vector<std::thread::id> owner(kCount);
std::vector<std::uint64_t> order(kCount, 0);
std::atomic<std::uint64_t> sequence{0};
const auto result = parallel_for(
0, kCount,
[&](int i) {
meter.enter();
owner[static_cast<std::size_t>(i)] = std::this_thread::get_id();
order[static_cast<std::size_t>(i)] = sequence.fetch_add(1);
hits[static_cast<std::size_t>(i)].fetch_add(1);
std::this_thread::sleep_for(1ms);
meter.leave();
},
pool, ParallelForOptions{.grain = 3, .max_concurrency = 2});
Void::Testing::expect(result.has_value());
int bad_hits = 0;
int chunk_not_on_one_thread = 0;
int chunk_not_ordered = 0;
for (int i = 0; i < kCount; ++i) {
if (hits[static_cast<std::size_t>(i)].load() != 1) {
++bad_hits;
}
if (i % 3 != 0) {
if (owner[static_cast<std::size_t>(i)] != owner[static_cast<std::size_t>(i - 1)]) {
++chunk_not_on_one_thread;
}
if (order[static_cast<std::size_t>(i)] <= order[static_cast<std::size_t>(i - 1)]) {
++chunk_not_ordered;
}
}
}
Void::Testing::expect_eq(bad_hits, 0);
Void::Testing::expect_eq(chunk_not_on_one_thread, 0);
Void::Testing::expect_eq(chunk_not_ordered, 0);
Void::Testing::expect(meter.peak.load() >= 1);
Void::Testing::expect(meter.peak.load() <= 2);
}
// max_concurrency == 0 means the pool's thread count.
{
ConcurrencyMeter meter;
std::atomic<int> calls{0};
const auto result = parallel_for(
0, 64,
[&](int) {
meter.enter();
calls.fetch_add(1);
std::this_thread::sleep_for(1ms);
meter.leave();
},
pool, ParallelForOptions{});
Void::Testing::expect(result.has_value());
Void::Testing::expect_eq(calls.load(), 64);
Void::Testing::expect(meter.peak.load() <= 4);
}
// The error report carries the chunk geometry: 40 indices / grain 3 = 14.
{
std::atomic<int> calls{0};
const auto result = parallel_for(
0, kCount,
[&](int i) {
calls.fetch_add(1);
if (i == 7) {
throw std::runtime_error{"seven"};
}
},
pool, ParallelForOptions{.grain = 3, .max_concurrency = 2, .stop_on_error = false});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind == Kind::failed);
Void::Testing::expect_eq(result.error().chunks_total, std::size_t{14});
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{14});
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{1});
Void::Testing::expect(result.error().first_failed_chunk == std::optional<std::size_t>{2});
Void::Testing::expect_eq(what(result.error().first_exception), std::string{"seven"});
// The throwing chunk [6, 9) stops at index 7; every other chunk ran fully.
Void::Testing::expect_eq(calls.load(), kCount - 1);
}
}
Void::Testing::Test parallel_for_bounded_signed_and_unsigned_ranges()
{
ThreadPool pool{3};
// Signed range crossing zero.
{
std::atomic<int> sum{0};
std::atomic<int> calls{0};
const auto result = parallel_for(
-5, 5, [&](int i) { sum.fetch_add(i); calls.fetch_add(1); }, pool,
ParallelForOptions{.grain = 4});
Void::Testing::expect(result.has_value());
Void::Testing::expect_eq(calls.load(), 10);
Void::Testing::expect_eq(sum.load(), -5);
}
// The whole int8 range: 255 indices computed in the unsigned type.
{
std::vector<std::atomic<int>> hits(256);
const auto result = parallel_for(
std::int8_t{-128}, std::int8_t{127},
[&](std::int8_t i) { hits[static_cast<std::size_t>(i + 128)].fetch_add(1); }, pool,
ParallelForOptions{.grain = 7});
Void::Testing::expect(result.has_value());
int wrong = 0;
for (std::size_t k = 0; k < 255; ++k) {
if (hits[k].load() != 1) {
++wrong;
}
}
Void::Testing::expect_eq(wrong, 0);
Void::Testing::expect_eq(hits[255].load(), 0);
}
// Top of the unsigned range, and a grain larger than the range.
{
std::atomic<int> calls{0};
std::atomic<std::uint64_t> sum{0};
const std::uint64_t top = std::numeric_limits<std::uint64_t>::max();
const auto result = parallel_for(
top - 3, top, [&](std::uint64_t i) { calls.fetch_add(1); sum.fetch_add(top - i); }, pool,
ParallelForOptions{.grain = 1000});
Void::Testing::expect(result.has_value());
Void::Testing::expect_eq(calls.load(), 3);
Void::Testing::expect_eq(sum.load(), std::uint64_t{3 + 2 + 1});
}
}
Void::Testing::Test parallel_for_bounded_stop_joins_started_no_new_chunks()
{
ThreadPool pool{2};
// One runner: chunk 0 requests stop; no later chunk may start.
{
std::stop_source stop;
std::atomic<int> started{0};
std::atomic<int> finished{0};
const auto result = parallel_for(
0, 100,
[&](int i) {
started.fetch_add(1);
if (i == 0) {
stop.request_stop();
std::this_thread::sleep_for(5ms);
}
finished.fetch_add(1);
},
pool, ParallelForOptions{.grain = 1, .max_concurrency = 1, .stop = stop.get_token()});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind == Kind::stopped);
Void::Testing::expect_eq(result.error().chunks_total, std::size_t{100});
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{1});
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{0});
Void::Testing::expect(!result.error().first_failed_chunk.has_value());
// The started chunk was joined (ran to completion) and nothing else ran.
Void::Testing::expect_eq(started.load(), 1);
Void::Testing::expect_eq(finished.load(), 1);
}
// Two runners: every chunk that started finishes; the rest never start.
{
std::stop_source stop;
std::atomic<int> started{0};
std::atomic<int> finished{0};
const auto result = parallel_for(
0, 1000,
[&](int i) {
started.fetch_add(1);
if (i == 3) {
stop.request_stop();
}
std::this_thread::sleep_for(1ms);
finished.fetch_add(1);
},
pool, ParallelForOptions{.grain = 1, .max_concurrency = 2, .stop = stop.get_token()});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind == Kind::stopped);
Void::Testing::expect_eq(started.load(), finished.load());
Void::Testing::expect_eq(result.error().chunks_started, static_cast<std::size_t>(started.load()));
Void::Testing::expect(result.error().chunks_started < std::size_t{1000});
Void::Testing::expect(result.error().chunks_started >= std::size_t{4});
}
// Stop requested before the call: nothing runs.
{
std::stop_source stop;
stop.request_stop();
std::atomic<int> calls{0};
const auto result = parallel_for(
0, 10, [&](int) { calls.fetch_add(1); }, pool,
ParallelForOptions{.stop = stop.get_token()});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind == Kind::stopped);
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{0});
Void::Testing::expect_eq(result.error().chunks_total, std::size_t{10});
Void::Testing::expect_eq(calls.load(), 0);
}
// A stop that arrives once every chunk has started is not an error.
{
std::stop_source stop;
std::atomic<int> calls{0};
const auto result = parallel_for(
0, 4,
[&](int i) {
calls.fetch_add(1);
if (i == 3) {
stop.request_stop();
}
},
pool, ParallelForOptions{.max_concurrency = 1, .stop = stop.get_token()});
Void::Testing::expect(result.has_value());
Void::Testing::expect_eq(calls.load(), 4);
}
}
Void::Testing::Test parallel_for_bounded_errors_join_all_lowest_index_reported()
{
ThreadPool pool{2};
// stop_on_error == false: every chunk runs; the lowest failed chunk wins
// even though higher chunks fail first or concurrently.
{
std::atomic<int> calls{0};
const auto result = parallel_for(
0, 10,
[&](int i) {
calls.fetch_add(1);
if (i == 5 || i == 2 || i == 8) {
throw std::runtime_error{"chunk " + std::to_string(i)};
}
},
pool, ParallelForOptions{.grain = 1, .max_concurrency = 2, .stop_on_error = false});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind == Kind::failed);
Void::Testing::expect_eq(calls.load(), 10);
Void::Testing::expect_eq(result.error().chunks_total, std::size_t{10});
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{10});
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{3});
Void::Testing::expect(result.error().first_failed_chunk == std::optional<std::size_t>{2});
Void::Testing::expect_eq(what(result.error().first_exception), std::string{"chunk 2"});
}
// stop_on_error == true: chunk 1 fails first, chunk 0 (already started)
// fails afterwards. The caller joins both and reports the LOWER chunk; no
// new chunk starts after the first failure.
{
std::atomic<bool> chunk_one_failed{false};
std::atomic<bool> chunk_zero_timed_out{false};
std::atomic<int> calls{0};
const auto result = parallel_for(
0, 10,
[&](int i) {
calls.fetch_add(1);
if (i == 0) {
const auto end = std::chrono::steady_clock::now() + 5s;
while (!chunk_one_failed.load() && std::chrono::steady_clock::now() < end) {
std::this_thread::yield();
}
if (!chunk_one_failed.load()) {
chunk_zero_timed_out.store(true);
}
throw std::runtime_error{"zero"};
}
if (i == 1) {
chunk_one_failed.store(true);
throw std::runtime_error{"one"};
}
},
pool, ParallelForOptions{.grain = 1, .max_concurrency = 2, .stop_on_error = true});
Void::Testing::require(!result.has_value());
Void::Testing::expect(!chunk_zero_timed_out.load());
Void::Testing::expect(result.error().kind == Kind::failed);
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{2});
Void::Testing::expect(result.error().first_failed_chunk == std::optional<std::size_t>{0});
Void::Testing::expect_eq(what(result.error().first_exception), std::string{"zero"});
// Only the two started chunks ran.
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{2});
Void::Testing::expect_eq(calls.load(), 2);
}
// `failed` outranks `stopped`.
{
std::stop_source stop;
const auto result = parallel_for(
0, 10,
[&](int i) {
if (i == 0) {
stop.request_stop();
throw std::runtime_error{"failed and stopped"};
}
},
pool, ParallelForOptions{.grain = 1, .max_concurrency = 1, .stop = stop.get_token()});
Void::Testing::require(!result.has_value());
Void::Testing::expect(result.error().kind == Kind::failed);
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{1});
}
// A non-std exception is preserved as an exception_ptr.
{
const auto result = parallel_for(
0, 3, [](int i) { if (i == 1) { throw 42; } }, pool,
ParallelForOptions{.grain = 1, .max_concurrency = 1, .stop_on_error = false});
Void::Testing::require(!result.has_value());
bool is_int = false;
try {
std::rethrow_exception(result.error().first_exception);
} catch (int value) {
is_int = value == 42;
} catch (...) {
}
Void::Testing::expect(is_int);
}
}
Void::Testing::Test parallel_for_bounded_zero_grain_invalid()
{
ThreadPool pool{2};
std::atomic<int> calls{0};
const auto zero_grain = parallel_for(
0, 10, [&](int) { calls.fetch_add(1); }, pool, ParallelForOptions{.grain = 0});
Void::Testing::require(!zero_grain.has_value());
Void::Testing::expect(zero_grain.error().kind == Kind::invalid_argument);
Void::Testing::expect_eq(zero_grain.error().chunks_total, std::size_t{0});
Void::Testing::expect_eq(zero_grain.error().chunks_started, std::size_t{0});
Void::Testing::expect_eq(calls.load(), 0);
// An empty or reversed range is a success and runs nothing.
const auto empty = parallel_for(5, 5, [&](int) { calls.fetch_add(1); }, pool, ParallelForOptions{});
Void::Testing::expect(empty.has_value());
const auto reversed = parallel_for(9, 2, [&](int) { calls.fetch_add(1); }, pool, ParallelForOptions{});
Void::Testing::expect(reversed.has_value());
Void::Testing::expect_eq(calls.load(), 0);
// The legacy overloads are unchanged.
std::atomic<int> legacy{0};
parallel_for(0, 5, [&](int) { legacy.fetch_add(1); }, pool);
Void::Testing::expect_eq(legacy.load(), 5);
}
Void::Testing::Test parallel_for_bounded_rejected_pool_runs_inline()
{
Gate gate;
std::atomic<bool> blocker_started{false};
{
// One worker, queue bound 1: occupy the worker and fill the queue so
// every try_submit is rejected.
ThreadPool pool{1, 1};
GateGuard guard{gate};
auto blocker = pool.submit([&] {
blocker_started.store(true);
gate.wait();
});
Void::Testing::require(wait_until([&] { return blocker_started.load(); }));
auto filler = pool.submit([] {});
Void::Testing::expect_eq(pool.pending_count(), std::size_t{1});
std::vector<std::thread::id> owner(20);
std::atomic<int> calls{0};
const auto caller = std::this_thread::get_id();
const auto result = parallel_for(
0, 20,
[&](int i) {
owner[static_cast<std::size_t>(i)] = std::this_thread::get_id();
calls.fetch_add(1);
},
pool, ParallelForOptions{.grain = 4, .max_concurrency = 3});
Void::Testing::expect(result.has_value());
Void::Testing::expect_eq(calls.load(), 20);
int off_caller = 0;
for (const auto& id : owner) {
if (id != caller) {
++off_caller;
}
}
// The pool rejected the runner, so the calling thread ran everything.
Void::Testing::expect_eq(off_caller, 0);
Void::Testing::expect(pool.stats().rejected >= 1);
gate.open();
blocker.get();
filler.get();
}
// Partial rejection: the caller joins the accepted runner but the bound
// on running chunks still holds (accepted runners + the caller).
{
ThreadPool pool{1, 1};
ConcurrencyMeter meter;
std::vector<std::atomic<int>> hits(30);
const auto result = parallel_for(
0, 30,
[&](int i) {
meter.enter();
hits[static_cast<std::size_t>(i)].fetch_add(1);
std::this_thread::sleep_for(1ms);
meter.leave();
},
pool, ParallelForOptions{.grain = 1, .max_concurrency = 2});
Void::Testing::expect(result.has_value());
int wrong = 0;
for (const auto& hit : hits) {
if (hit.load() != 1) {
++wrong;
}
}
Void::Testing::expect_eq(wrong, 0);
Void::Testing::expect(meter.peak.load() <= 2);
}
}
Void::Testing::Test parallel_for_bounded_waits_all_submitted_runners()
{
Gate gate;
std::atomic<bool> blocker_started{false};
std::atomic<bool> returned{false};
std::atomic<int> calls{0};
std::optional<std::expected<void, ParallelForError>> outcome;
std::stop_source stop;
ThreadPool pool{1};
GateGuard guard{gate};
auto blocker = pool.submit([&] {
blocker_started.store(true);
gate.wait();
});
Void::Testing::require(wait_until([&] { return blocker_started.load(); }));
// Three runners queue behind the blocker and cannot start. The caller must
// still wait for every one of them, also after a stop was requested.
std::thread caller([&] {
outcome = parallel_for(
0, 100, [&](int) { calls.fetch_add(1); }, pool,
ParallelForOptions{.grain = 10, .max_concurrency = 3, .stop = stop.get_token()});
returned.store(true);
});
ThreadJoiner joiner{gate, caller};
Void::Testing::expect(wait_until([&] { return pool.pending_count() == 3; }));
stop.request_stop();
std::this_thread::sleep_for(60ms);
Void::Testing::expect(!returned.load());
gate.open();
caller.join();
blocker.get();
Void::Testing::expect(returned.load());
Void::Testing::require(outcome.has_value());
Void::Testing::require(!outcome->has_value());
Void::Testing::expect((*outcome).error().kind == Kind::stopped);
// The runners found the stop request: no chunk ever started.
Void::Testing::expect_eq((*outcome).error().chunks_started, std::size_t{0});
Void::Testing::expect_eq((*outcome).error().chunks_total, std::size_t{10});
Void::Testing::expect_eq(calls.load(), 0);
// Every runner future was waited for: the queue is empty.
Void::Testing::expect_eq(pool.pending_count(), std::size_t{0});
}
Void::Testing::Test legacy_parallel_for_exception_joins_all()
{
ThreadPool pool{2};
std::atomic<int> finished{0};
bool caught = false;
try {
parallel_for(0, 8, [&](int i) {
if (i == 0) {
throw std::runtime_error{"first"};
}
std::this_thread::sleep_for(25ms);
finished.fetch_add(1);
}, pool);
} catch (const std::runtime_error& error) {
caught = std::string{error.what()} == "first";
}
Void::Testing::expect(caught);
// The exception surfaced only after every other task finished; none is
// still running against this stack.
Void::Testing::expect_eq(finished.load(), 7);
// With several failures the first (lowest index) is rethrown.
std::atomic<int> second_finished{0};
std::string message;
try {
parallel_for(0, 6, [&](int i) {
std::this_thread::sleep_for(5ms);
second_finished.fetch_add(1);
if (i == 1 || i == 3) {
throw std::runtime_error{"error " + std::to_string(i)};
}
}, pool);
} catch (const std::runtime_error& error) {
message = error.what();
}
Void::Testing::expect_eq(message, std::string{"error 1"});
Void::Testing::expect_eq(second_finished.load(), 6);
}
+881
View File
@@ -0,0 +1,881 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/TaskScope.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <coroutine>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <functional>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <system_error>
#include <thread>
#include <utility>
#include <vector>
// Every assertion runs on the test thread: jobs executed by workers only touch
// atomics or mutex-guarded containers (the assertion context is thread_local).
namespace
{
using namespace Void::Async;
using namespace std::chrono_literals;
// Detached, self-destroying coroutine frame created suspended: a handle to
// post. A job that is never resumed must be destroy()ed by its creator.
struct Job {
struct promise_type {
Job get_return_object() noexcept
{
return Job{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{};
};
Job make_job(std::function<void()> body)
{
body();
co_return;
}
class Gate
{
public:
void open()
{
{
std::lock_guard lk{mu_};
open_ = true;
}
cv_.notify_all();
}
void wait()
{
std::unique_lock lk{mu_};
cv_.wait(lk, [this] { return open_; });
}
private:
std::mutex mu_{};
std::condition_variable cv_{};
bool open_{false};
};
template <class Pred>
bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms)
{
const auto end = std::chrono::steady_clock::now() + timeout;
while (!pred()) {
if (std::chrono::steady_clock::now() >= end) {
return false;
}
std::this_thread::sleep_for(1ms);
}
return true;
}
// Owns the executor and a gate. The destructor opens the gate FIRST, so a
// failed assertion can never leave a blocker job hanging ~ThreadExecutor, then
// destroys the executor (which joins) and finally the gate.
struct Fixture {
Gate gate{};
std::unique_ptr<ThreadExecutor> exec{};
Fixture(std::size_t workers, std::size_t max_admitted, bool start = true)
{
auto created = ThreadExecutor::create(
ThreadExecutorOptions{.workers = workers, .max_admitted = max_admitted});
Void::Testing::require(created.has_value());
exec = std::move(*created);
if (start) {
Void::Testing::require(exec->start().has_value());
}
}
~Fixture() { gate.open(); }
Fixture(const Fixture&) = delete;
Fixture& operator=(const Fixture&) = delete;
ThreadExecutor& operator*() { return *exec; }
ThreadExecutor* operator->() { return exec.get(); }
};
// A job that occupies a worker until the fixture gate opens.
Job make_blocker(Fixture& fx, std::atomic<bool>& running)
{
return make_job([&fx, &running] {
running.store(true, std::memory_order_release);
fx.gate.wait();
});
}
std::optional<AsyncErrorCode> async_code(const Void::Result::Error& error)
{
if (error.code().domain != Void::Result::kAsyncErrorDomain) {
return std::nullopt;
}
return static_cast<AsyncErrorCode>(error.code().value);
}
Void::Coro::Task<void> bump_task(std::atomic<int>* counter)
{
counter->fetch_add(1, std::memory_order_relaxed);
co_return;
}
// Posts `job` through one of the four admission paths (retrying while the
// bound is full). Returns false (and destroys the frame) on an unexpected
// rejection. Assertion free: runs on poster threads.
bool post_one(ThreadExecutor& exec, int kind, Job& job)
{
switch (kind) {
case 0:
for (;;) {
const auto admitted = exec.try_post(job.handle);
if (admitted.has_value()) {
return true;
}
if (admitted.error() != AdmissionError::overloaded) {
job.handle.destroy();
return false;
}
std::this_thread::yield();
}
case 1:
exec.post(job.handle);
return true;
case 2:
exec.post_completion(job.handle);
return true;
default:
for (;;) {
const auto reserved = exec.try_reserve_slot();
if (reserved.has_value()) {
break;
}
if (reserved.error() != AdmissionError::overloaded) {
job.handle.destroy();
return false;
}
std::this_thread::yield();
}
exec.commit_reserved(job.handle);
return true;
}
}
} // namespace
Void::Testing::Test thread_executor_create_starts_no_threads()
{
std::atomic<int> hook_calls{0};
std::atomic<int> ran{0};
auto created = ThreadExecutor::create(ThreadExecutorOptions{
.workers = 2,
.max_admitted = 4,
.before_worker_start = [&hook_calls](std::size_t) -> Void::Result::Result<void> {
hook_calls.fetch_add(1);
return {};
}});
Void::Testing::require(created.has_value());
auto& exec = **created;
// No thread (and no hook call) exists yet.
Void::Testing::expect_eq(hook_calls.load(), 0);
Void::Testing::expect(exec.idle());
Void::Testing::expect_eq(exec.admitted(), std::size_t{0});
Void::Testing::expect(exec.supports_reservation());
Void::Testing::expect(exec.has_background_workers());
// Admission before start() queues normally and nothing runs.
auto job = make_job([&ran] { ran.fetch_add(1); });
Void::Testing::require(exec.try_post(job.handle).has_value());
Void::Testing::expect_eq(exec.admitted(), std::size_t{1});
std::this_thread::sleep_for(30ms);
Void::Testing::expect_eq(ran.load(), 0);
Void::Testing::expect_eq(exec.stats().queued, std::size_t{1});
Void::Testing::expect(!exec.idle());
Void::Testing::require(exec.start().has_value());
Void::Testing::expect_eq(hook_calls.load(), 2);
Void::Testing::expect(wait_until([&] { return ran.load() == 1; }));
Void::Testing::require(exec.join().has_value());
// create() validates its options.
const auto zero_workers = ThreadExecutor::create(ThreadExecutorOptions{.workers = 0});
Void::Testing::require(!zero_workers.has_value());
Void::Testing::expect(async_code(zero_workers.error()) == AsyncErrorCode::invalid_argument);
const auto zero_bound = ThreadExecutor::create(ThreadExecutorOptions{.max_admitted = 0});
Void::Testing::require(!zero_bound.has_value());
Void::Testing::expect(async_code(zero_bound.error()) == AsyncErrorCode::invalid_argument);
}
Void::Testing::Test thread_executor_bound_includes_running_work()
{
std::atomic<bool> blocker_running{false};
std::atomic<int> ran{0};
Fixture exec{1, 2};
auto blocker = make_blocker(exec, blocker_running);
Void::Testing::require(exec->try_post(blocker.handle).has_value());
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
// The running blocker keeps its slot.
Void::Testing::expect_eq(exec->admitted(), std::size_t{1});
Void::Testing::expect_eq(exec->stats().running, std::size_t{1});
auto queued = make_job([&ran] { ran.fetch_add(1); });
Void::Testing::require(exec->try_post(queued.handle).has_value());
Void::Testing::expect_eq(exec->admitted(), std::size_t{2});
// running (1) + queued (1) == max_admitted (2): the next one is rejected.
auto rejected = make_job([&ran] { ran.fetch_add(100); });
const auto overloaded = exec->try_post(rejected.handle);
Void::Testing::expect(!overloaded.has_value());
Void::Testing::expect(overloaded.error() == AdmissionError::overloaded);
rejected.handle.destroy();
Void::Testing::expect_eq(exec->stats().rejected, std::uint64_t{1});
Void::Testing::expect_eq(exec->stats().queued, std::size_t{1});
// Legacy post() never rejects: it may exceed the bound and is counted.
auto legacy = make_job([&ran] { ran.fetch_add(10); });
exec->post(legacy.handle);
Void::Testing::expect_eq(exec->admitted(), std::size_t{3});
Void::Testing::expect_eq(exec->stats().legacy_posts, std::uint64_t{1});
// A null handle is invalid for try_post.
const auto null_handle = exec->try_post({});
Void::Testing::expect(!null_handle.has_value());
Void::Testing::expect(null_handle.error() == AdmissionError::invalid_argument);
exec.gate.open();
Void::Testing::expect(wait_until([&] { return ran.load() == 11 && exec->idle(); }));
// A slot is free again once the work returned.
auto again = make_job([&ran] { ran.fetch_add(1000); });
Void::Testing::require(exec->try_post(again.handle).has_value());
Void::Testing::expect(wait_until([&] { return ran.load() == 1011; }));
Void::Testing::expect(wait_until([&] { return exec->admitted() == 0; }));
}
Void::Testing::Test thread_executor_reservation_with_task_scope_preserves_task()
{
std::atomic<bool> blocker_running{false};
std::atomic<int> ran{0};
Fixture exec{1, 1};
TaskScope scope{*exec, TaskScopeOptions{.max_tasks = 8}};
auto blocker = make_blocker(exec, blocker_running);
Void::Testing::require(exec->try_post(blocker.handle).has_value());
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
// The bound is full: TaskScope's reserve-then-transfer is rejected and the
// caller still owns the task.
auto preserved = bump_task(&ran);
const auto rejected = scope.spawn(std::move(preserved));
Void::Testing::require(!rejected.has_value());
Void::Testing::expect(rejected.error() == AdmissionError::overloaded);
Void::Testing::expect(static_cast<bool>(preserved.handle()));
Void::Testing::expect(!preserved.done());
// The failed reservation did not leak a slot.
Void::Testing::expect_eq(exec->admitted(), std::size_t{1});
Void::Testing::expect_eq(ran.load(), 0);
exec.gate.open();
Void::Testing::require(wait_until([&] { return exec->admitted() == 0; }));
const auto accepted = scope.spawn(std::move(preserved));
Void::Testing::require(accepted.has_value());
Void::Testing::require(scope.join_blocking().has_value());
Void::Testing::expect_eq(ran.load(), 1);
Void::Testing::expect(wait_until([&] { return exec->admitted() == 0; }));
}
Void::Testing::Test thread_executor_completion_lane_bypasses_full_normal_lane()
{
std::atomic<bool> blocker_running{false};
std::atomic<int> completion_ran{0};
Fixture exec{1, 1};
auto blocker = make_blocker(exec, blocker_running);
Void::Testing::require(exec->try_post(blocker.handle).has_value());
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
// The normal lane is full ...
auto normal = make_job([] {});
const auto overloaded = exec->try_post(normal.handle);
Void::Testing::expect(!overloaded.has_value());
normal.handle.destroy();
const auto reserve_rejected = exec->try_reserve_slot();
Void::Testing::expect(!reserve_rejected.has_value());
Void::Testing::expect(reserve_rejected.error() == AdmissionError::overloaded);
// ... but the completion lane still accepts and is not part of the bound.
auto completion = make_job([&completion_ran] { completion_ran.fetch_add(1); });
exec->post_completion(completion.handle);
Void::Testing::expect_eq(exec->stats().completion_queued, std::size_t{1});
Void::Testing::expect_eq(exec->admitted(), std::size_t{1});
exec.gate.open();
Void::Testing::expect(wait_until([&] { return completion_ran.load() == 1; }));
Void::Testing::expect(wait_until([&] { return exec->idle(); }));
}
Void::Testing::Test thread_executor_close_rejects_normal_drains_completion()
{
std::atomic<bool> blocker_running{false};
std::atomic<int> order_counter{0};
std::atomic<int> completion_order{-1};
std::atomic<int> legacy_order{-1};
std::atomic<int> queued_order{-1};
Fixture exec{1, 8};
auto blocker = make_blocker(exec, blocker_running);
Void::Testing::require(exec->try_post(blocker.handle).has_value());
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
auto queued = make_job([&] { queued_order.store(order_counter.fetch_add(1)); });
Void::Testing::require(exec->try_post(queued.handle).has_value());
exec->close();
// Normal admission is closed.
auto refused = make_job([] {});
const auto stopped_post = exec->try_post(refused.handle);
Void::Testing::expect(!stopped_post.has_value());
Void::Testing::expect(stopped_post.error() == AdmissionError::stopped);
refused.handle.destroy();
const auto stopped_reserve = exec->try_reserve_slot();
Void::Testing::expect(!stopped_reserve.has_value());
Void::Testing::expect(stopped_reserve.error() == AdmissionError::stopped);
// A legacy post after close() is redirected to the completion lane and
// counted; post_completion keeps working.
auto legacy = make_job([&] { legacy_order.store(order_counter.fetch_add(1)); });
exec->post(legacy.handle);
auto completion = make_job([&] { completion_order.store(order_counter.fetch_add(1)); });
exec->post_completion(completion.handle);
Void::Testing::expect_eq(exec->stats().completion_queued, std::size_t{2});
Void::Testing::expect_eq(exec->stats().legacy_posts, std::uint64_t{1});
exec.gate.open();
Void::Testing::require(exec->join().has_value());
// Both lanes drained; the completion lane (legacy post, then the explicit
// completion) runs before the queued normal handle.
Void::Testing::expect_eq(legacy_order.load(), 0);
Void::Testing::expect_eq(completion_order.load(), 1);
Void::Testing::expect_eq(queued_order.load(), 2);
Void::Testing::expect(exec->idle());
}
Void::Testing::Test thread_executor_join_self_join_on_worker()
{
std::atomic<int> code{-1};
std::atomic<bool> observed_executor_thread{false};
Fixture exec{1, 4};
auto job = make_job([&] {
const auto joined = exec->join();
code.store(joined.has_value() ? 0 : static_cast<int>(joined.error().code().value));
observed_executor_thread.store(exec->is_executor_thread());
});
Void::Testing::require(exec->try_post(job.handle).has_value());
Void::Testing::require(wait_until([&] { return code.load() != -1; }));
Void::Testing::expect_eq(code.load(), static_cast<int>(AsyncErrorCode::self_join));
Void::Testing::expect(observed_executor_thread.load());
// A normal join from a non-executor thread still works afterwards.
Void::Testing::expect(!exec->is_executor_thread());
Void::Testing::require(exec->join().has_value());
}
Void::Testing::Test thread_executor_partial_start_failure_joins_started()
{
std::atomic<int> hook_calls{0};
std::atomic<bool> fail{true};
std::atomic<int> ran{0};
auto created = ThreadExecutor::create(ThreadExecutorOptions{
.workers = 3,
.max_admitted = 8,
.before_worker_start = [&](std::size_t index) -> Void::Result::Result<void> {
hook_calls.fetch_add(1);
if (fail.load() && index == 2) {
return std::unexpected{make_async_error(
AsyncErrorCode::limit_exceeded, "injected thread start failure")};
}
return {};
}});
Void::Testing::require(created.has_value());
auto& exec = **created;
// Work admitted before start() must not run on workers of a failed start.
auto job = make_job([&ran] { ran.fetch_add(1); });
Void::Testing::require(exec.try_post(job.handle).has_value());
const auto failed = exec.start();
Void::Testing::require(!failed.has_value());
Void::Testing::expect(async_code(failed.error()) == AsyncErrorCode::limit_exceeded);
Void::Testing::expect_eq(hook_calls.load(), 3);
std::this_thread::sleep_for(30ms);
Void::Testing::expect_eq(ran.load(), 0);
Void::Testing::expect_eq(exec.stats().queued, std::size_t{1});
Void::Testing::expect_eq(exec.stats().running, std::size_t{0});
// The two workers that were already started were joined: a retry starts a
// full set again.
fail.store(false);
Void::Testing::require(exec.start().has_value());
Void::Testing::expect_eq(hook_calls.load(), 6);
Void::Testing::expect(wait_until([&] { return ran.load() == 1; }));
Void::Testing::require(exec.join().has_value());
}
Void::Testing::Test thread_executor_system_error_path_shared_with_hook()
{
std::atomic<int> mode{0}; // 0 = ok, 1 = system_error, 2 = runtime_error
std::atomic<int> hook_calls{0};
std::atomic<int> ran{0};
auto created = ThreadExecutor::create(ThreadExecutorOptions{
.workers = 3,
.max_admitted = 8,
.before_worker_start = [&](std::size_t index) -> Void::Result::Result<void> {
hook_calls.fetch_add(1);
if (index == 1 && mode.load() == 1) {
throw std::system_error{std::make_error_code(std::errc::resource_unavailable_try_again),
"injected thread creation failure"};
}
if (index == 1 && mode.load() == 2) {
throw std::runtime_error{"injected hook failure"};
}
return {};
}});
Void::Testing::require(created.has_value());
auto& exec = **created;
auto job = make_job([&ran] { ran.fetch_add(1); });
Void::Testing::require(exec.try_post(job.handle).has_value());
// std::system_error: same cleanup path as a hook error, system code kept.
mode.store(1);
const auto sys_failed = exec.start();
Void::Testing::require(!sys_failed.has_value());
Void::Testing::expect(async_code(sys_failed.error()) == AsyncErrorCode::backend_error);
Void::Testing::expect(sys_failed.error().system_code() ==
std::make_error_code(std::errc::resource_unavailable_try_again));
Void::Testing::expect_eq(hook_calls.load(), 2);
// Any other exception takes the same path, without a system code.
mode.store(2);
const auto other_failed = exec.start();
Void::Testing::require(!other_failed.has_value());
Void::Testing::expect(async_code(other_failed.error()) == AsyncErrorCode::backend_error);
Void::Testing::expect(!other_failed.error().system_code());
Void::Testing::expect_eq(hook_calls.load(), 4);
Void::Testing::expect_eq(ran.load(), 0);
mode.store(0);
Void::Testing::require(exec.start().has_value());
Void::Testing::expect(wait_until([&] { return ran.load() == 1; }));
Void::Testing::require(exec.join().has_value());
}
namespace
{
Void::Coro::Task<void> hop_task(ThreadExecutor* exec,
std::atomic<int>* stage,
std::atomic<bool>* on_executor_before,
std::atomic<bool>* on_executor_after,
std::atomic<int>* status_code)
{
on_executor_before->store(exec->is_executor_thread());
stage->store(1);
co_await schedule_on(*exec);
stage->store(2);
const auto status = co_await schedule_on(*exec, OperationOptions{});
status_code->store(status.has_value() ? 0 : static_cast<int>(status.error().code().value));
on_executor_after->store(exec->is_executor_thread());
stage->store(3);
}
} // namespace
Void::Testing::Test thread_executor_legacy_post_spawn_schedule_on_compat()
{
std::atomic<int> stage{0};
std::atomic<bool> before{false};
std::atomic<bool> after{false};
std::atomic<int> status_code{-1};
std::atomic<bool> blocker_running{false};
std::atomic<int> ran{0};
Fixture exec{1, 2};
// spawn() and schedule_on(executor) use the legacy post(): never rejected.
// spawn() is called from the single worker itself, not from a foreign
// thread: ThreadSanitizer reports a data race in Executor.hpp's spawn_impl
// (lines 292/296) when spawn() is called from a thread other than the
// executor's workers onto a multi-worker executor. That behaviour is
// independent of ThreadExecutor and is escalated to the root; it is not
// covered here.
auto spawner = make_job([&] {
spawn(*exec, hop_task(exec.exec.get(), &stage, &before, &after, &status_code));
});
Void::Testing::require(exec->try_post(spawner.handle).has_value());
Void::Testing::require(wait_until([&] { return stage.load() == 3; }));
Void::Testing::expect(before.load());
Void::Testing::expect(after.load());
Void::Testing::expect_eq(status_code.load(), 0);
Void::Testing::expect(exec->stats().legacy_posts >= 2);
// A full bound (running + queued == 2) rejects try_post (and the status
// schedule_on built on it) but never the legacy post.
auto blocker = make_blocker(exec, blocker_running);
Void::Testing::require(exec->try_post(blocker.handle).has_value());
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
auto filler = make_job([&ran] { ran.fetch_add(1); });
Void::Testing::require(exec->try_post(filler.handle).has_value());
auto rejected = make_job([] {});
Void::Testing::expect(!exec->try_post(rejected.handle).has_value());
rejected.handle.destroy();
const std::uint64_t legacy_before = exec->stats().legacy_posts;
auto j1 = make_job([&ran] { ran.fetch_add(1); });
auto j2 = make_job([&ran] { ran.fetch_add(1); });
exec->post(j1.handle);
exec->post(j2.handle);
Void::Testing::expect_eq(exec->stats().legacy_posts, legacy_before + 2);
Void::Testing::expect_eq(exec->admitted(), std::size_t{4});
exec.gate.open();
Void::Testing::expect(wait_until([&] { return ran.load() == 3; }));
Void::Testing::require(exec->join().has_value());
}
Void::Testing::Test thread_executor_inline_after_join_counted()
{
std::atomic<int> ran{0};
std::mutex mu;
std::vector<std::thread::id> threads;
std::atomic<bool> guarded{false};
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 4});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.start().has_value());
auto before_join = make_job([&] { ran.fetch_add(1); });
Void::Testing::require(exec.try_post(before_join.handle).has_value());
Void::Testing::require(exec.join().has_value());
Void::Testing::expect_eq(ran.load(), 1);
Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{0});
// After join, posts resume inline on the caller (counted), never dropped.
const auto caller = std::this_thread::get_id();
auto record = [&] {
std::lock_guard lk{mu};
threads.push_back(std::this_thread::get_id());
guarded.store(exec.is_executor_thread());
};
auto j1 = make_job(record);
exec.post(j1.handle);
auto j2 = make_job(record);
exec.post_completion(j2.handle);
Void::Testing::expect_eq(threads.size(), std::size_t{2});
Void::Testing::expect(threads[0] == caller);
Void::Testing::expect(threads[1] == caller);
// The inline resume runs under ExecutorThreadGuard.
Void::Testing::expect(guarded.load());
Void::Testing::expect(!exec.is_executor_thread());
Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{2});
Void::Testing::expect_eq(exec.stats().legacy_posts, std::uint64_t{1});
// Normal admission stays closed after join, and join/start are repeatable
// or rejected.
auto refused = make_job([] {});
const auto stopped = exec.try_post(refused.handle);
Void::Testing::expect(!stopped.has_value());
Void::Testing::expect(stopped.error() == AdmissionError::stopped);
refused.handle.destroy();
const auto reserved = exec.try_reserve_slot();
Void::Testing::expect(!reserved.has_value());
Void::Testing::expect(reserved.error() == AdmissionError::stopped);
Void::Testing::require(exec.join().has_value());
const auto restarted = exec.start();
Void::Testing::expect(!restarted.has_value());
Void::Testing::expect(exec.idle());
}
Void::Testing::Test thread_executor_join_without_start_drains_inline()
{
std::mutex mu;
std::vector<int> order;
std::atomic<bool> all_on_caller{true};
const auto caller = std::this_thread::get_id();
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 8});
Void::Testing::require(created.has_value());
auto& exec = **created;
auto make_marker = [&](int id) {
return make_job([&, id] {
std::lock_guard lk{mu};
order.push_back(id);
if (std::this_thread::get_id() != caller) {
all_on_caller.store(false);
}
});
};
auto n1 = make_marker(1);
auto n2 = make_marker(2);
auto c1 = make_marker(10);
auto n3 = make_marker(3);
Void::Testing::require(exec.try_post(n1.handle).has_value());
Void::Testing::require(exec.try_post(n2.handle).has_value());
exec.post_completion(c1.handle);
exec.post(n3.handle);
Void::Testing::expect_eq(exec.admitted(), std::size_t{3});
// No worker exists: join() drains both lanes inline, never waits.
Void::Testing::require(exec.join().has_value());
Void::Testing::expect(all_on_caller.load());
// Completion lane first, then the normal lane in FIFO order.
Void::Testing::expect_eq(order.size(), std::size_t{4});
if (order.size() == 4) {
Void::Testing::expect_eq(order[0], 10);
Void::Testing::expect_eq(order[1], 1);
Void::Testing::expect_eq(order[2], 2);
Void::Testing::expect_eq(order[3], 3);
}
Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{4});
Void::Testing::expect(exec.idle());
Void::Testing::expect(!exec.start().has_value());
// The destructor of a never-started executor also drains inline.
std::atomic<int> ran{0};
{
auto second = ThreadExecutor::create();
Void::Testing::require(second.has_value());
auto pending = make_job([&ran] { ran.fetch_add(1); });
Void::Testing::require((*second)->try_post(pending.handle).has_value());
}
Void::Testing::expect_eq(ran.load(), 1);
}
Void::Testing::Test thread_executor_start_twice_and_after_close_invalid()
{
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 4});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.start().has_value());
const auto twice = exec.start();
Void::Testing::require(!twice.has_value());
Void::Testing::expect(async_code(twice.error()) == AsyncErrorCode::invalid_argument);
auto closed_created = ThreadExecutor::create();
Void::Testing::require(closed_created.has_value());
auto& closed = **closed_created;
closed.close();
const auto after_close = closed.start();
Void::Testing::require(!after_close.has_value());
Void::Testing::expect(async_code(after_close.error()) == AsyncErrorCode::invalid_argument);
Void::Testing::require(exec.join().has_value());
const auto after_join = exec.start();
Void::Testing::require(!after_join.has_value());
Void::Testing::expect(async_code(after_join.error()) == AsyncErrorCode::invalid_argument);
}
Void::Testing::Test thread_executor_reservation_across_close_binding()
{
std::atomic<int> ran{0};
std::atomic<bool> joined{false};
std::atomic<bool> join_ok{false};
std::atomic<bool> job_on_joiner{false};
// (1) Workers running: a reservation taken before close() stays binding.
{
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.start().has_value());
Void::Testing::require(exec.try_reserve_slot().has_value());
// A reserved slot counts in admitted() and in the bound.
Void::Testing::expect_eq(exec.admitted(), std::size_t{1});
Void::Testing::require(exec.try_reserve_slot().has_value());
const auto full = exec.try_reserve_slot();
Void::Testing::expect(!full.has_value());
Void::Testing::expect(full.error() == AdmissionError::overloaded);
exec.release_reserved();
Void::Testing::expect_eq(exec.admitted(), std::size_t{1});
exec.close();
const auto after_close = exec.try_reserve_slot();
Void::Testing::expect(!after_close.has_value());
Void::Testing::expect(after_close.error() == AdmissionError::stopped);
Void::Testing::expect_eq(exec.admitted(), std::size_t{1});
std::thread joiner([&] {
join_ok.store(exec.join().has_value());
joined.store(true);
});
// join() also waits until no reservation is outstanding.
std::this_thread::sleep_for(60ms);
Void::Testing::expect(!joined.load());
auto job = make_job([&ran] { ran.fetch_add(1); });
exec.commit_reserved(job.handle); // binding: enqueues normally after close()
joiner.join();
Void::Testing::expect(joined.load());
Void::Testing::expect(join_ok.load());
Void::Testing::expect_eq(ran.load(), 1);
Void::Testing::expect_eq(exec.admitted(), std::size_t{0});
}
// (2) A released reservation also lets join() finish (no workers: the
// joiner drains inline, but still waits for the reservation).
{
joined.store(false);
join_ok.store(false);
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.try_reserve_slot().has_value());
std::thread joiner([&] {
join_ok.store(exec.join().has_value());
joined.store(true);
});
std::this_thread::sleep_for(60ms);
Void::Testing::expect(!joined.load());
exec.release_reserved();
joiner.join();
Void::Testing::expect(joined.load());
Void::Testing::expect(join_ok.load());
}
// (3) No workers + a commit after join() began: the committed handle is
// drained by the joining thread.
{
joined.store(false);
join_ok.store(false);
const auto joiner_id = std::make_shared<std::atomic<std::thread::id>>();
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.try_reserve_slot().has_value());
std::thread joiner([&] {
joiner_id->store(std::this_thread::get_id());
join_ok.store(exec.join().has_value());
joined.store(true);
});
std::this_thread::sleep_for(60ms);
auto job = make_job([&] {
job_on_joiner.store(std::this_thread::get_id() == joiner_id->load());
ran.fetch_add(1);
});
exec.commit_reserved(job.handle);
joiner.join();
Void::Testing::expect(join_ok.load());
Void::Testing::expect(job_on_joiner.load());
Void::Testing::expect_eq(ran.load(), 2);
}
}
Void::Testing::Test thread_executor_stress_tsan()
{
constexpr int kPosters = 4;
constexpr int kPerPoster = 1200;
std::atomic<std::uint64_t> accepted{0};
std::atomic<std::uint64_t> executed{0};
std::atomic<std::uint64_t> posted_failed_unexpectedly{0};
std::atomic<std::uint64_t> snapshot_inconsistent{0};
std::vector<std::thread> posters;
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 3, .max_admitted = 32});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.start().has_value());
for (int p = 0; p < kPosters; ++p) {
posters.emplace_back([&, p] {
for (int k = 0; k < kPerPoster; ++k) {
const int kind = (p + k) % 4;
auto job = make_job([&executed] { executed.fetch_add(1, std::memory_order_relaxed); });
if (post_one(exec, kind, job)) {
accepted.fetch_add(1, std::memory_order_relaxed);
} else {
posted_failed_unexpectedly.fetch_add(1);
}
if ((k & 63) == 0) {
const auto stats = exec.stats();
if (stats.running > 3) {
snapshot_inconsistent.fetch_add(1);
}
(void)exec.idle();
}
}
});
}
for (auto& poster : posters) {
poster.join();
}
// Repeated and concurrent join(): every caller returns success and the
// worker threads are joined exactly once.
std::atomic<int> concurrent_join_failures{0};
std::vector<std::thread> joiners;
for (int j = 0; j < 3; ++j) {
joiners.emplace_back([&] {
if (!exec.join().has_value()) {
concurrent_join_failures.fetch_add(1);
}
});
}
const bool main_join_ok = exec.join().has_value();
for (auto& joiner : joiners) {
joiner.join();
}
Void::Testing::require(main_join_ok);
Void::Testing::expect_eq(concurrent_join_failures.load(), 0);
Void::Testing::expect_eq(posted_failed_unexpectedly.load(), std::uint64_t{0});
Void::Testing::expect_eq(snapshot_inconsistent.load(), std::uint64_t{0});
Void::Testing::expect_eq(accepted.load(), static_cast<std::uint64_t>(kPosters) * kPerPoster);
Void::Testing::expect_eq(executed.load(), accepted.load());
Void::Testing::expect(exec.idle());
Void::Testing::expect_eq(exec.admitted(), std::size_t{0});
}
// Regression (W11): spawn() from a foreign thread onto a multi-worker executor
// must not race with the worker that resumes and destroys the detached frame.
namespace
{
Void::Coro::Task<void> spawn_bump(std::atomic<int>* counter)
{
counter->fetch_add(1, std::memory_order_relaxed);
co_return;
}
} // namespace
Void::Testing::Test thread_executor_spawn_from_foreign_thread_multi_worker_tsan()
{
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 4, .max_admitted = 64});
Void::Testing::require(created.has_value());
auto& exec = **created;
Void::Testing::require(exec.start().has_value());
constexpr int kSpawns = 2000;
std::atomic<int> counter{0};
for (int i = 0; i < kSpawns; ++i) {
spawn(exec, spawn_bump(&counter));
}
Void::Testing::require(exec.join().has_value());
Void::Testing::expect_eq(counter.load(std::memory_order_relaxed), kSpawns);
}