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

@@ -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);
}