Files
Library/include/Void/Async/ParallelFor.hpp
T

337 lines
11 KiB
C++

#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
{
// 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)
{
if (first >= last) {
return;
}
std::vector<std::future<void>> futures;
futures.reserve(static_cast<std::size_t>(last - first));
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) {
try {
fut.get();
} catch (...) {
if (!first_error) {
first_error = std::current_exception();
}
}
}
if (first_error) {
std::rethrow_exception(first_error);
}
}
// Convenience overload that creates a temporary pool sized to hardware
// concurrency.
template <std::integral I, std::invocable<I> F>
void parallel_for(I first, I last, F&& f)
{
ThreadPool pool;
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