feat(async): add ThreadExecutor, FuturePool, AsyncChannel, bounded parallel_for, and spawn fix (M-ASYNC-04)
This commit is contained in:
1 parent
5c24f8e84f
commit
b2c84114fe
9 files changed
+4763
-8
No files matched your search
@@ -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
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user