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
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,245 @@
|
||||
#include <Void/Async/FuturePool.hpp>
|
||||
#include <Void/Async/ThreadExecutor.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
// All assertions run on the test thread; callables executed by workers only
|
||||
// touch atomics (the assertion context is thread_local).
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using namespace Void::Async;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
class Gate
|
||||
{
|
||||
public:
|
||||
void open()
|
||||
{
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
open_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
}
|
||||
|
||||
void wait()
|
||||
{
|
||||
std::unique_lock lk{mu_};
|
||||
cv_.wait(lk, [this] { return open_; });
|
||||
}
|
||||
|
||||
private:
|
||||
std::mutex mu_{};
|
||||
std::condition_variable cv_{};
|
||||
bool open_{false};
|
||||
};
|
||||
|
||||
template <class Pred>
|
||||
bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms)
|
||||
{
|
||||
const auto end = std::chrono::steady_clock::now() + timeout;
|
||||
while (!pred()) {
|
||||
if (std::chrono::steady_clock::now() >= end) {
|
||||
return false;
|
||||
}
|
||||
std::this_thread::sleep_for(1ms);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Opens the gate before the executor is destroyed, so a failed assertion can
|
||||
// never leave a blocked callable hanging ~ThreadExecutor.
|
||||
struct Fixture {
|
||||
Gate gate{};
|
||||
std::unique_ptr<ThreadExecutor> exec{};
|
||||
|
||||
Fixture(std::size_t workers, std::size_t max_admitted)
|
||||
{
|
||||
auto created = ThreadExecutor::create(
|
||||
ThreadExecutorOptions{.workers = workers, .max_admitted = max_admitted});
|
||||
Void::Testing::require(created.has_value());
|
||||
exec = std::move(*created);
|
||||
Void::Testing::require(exec->start().has_value());
|
||||
}
|
||||
|
||||
~Fixture() { gate.open(); }
|
||||
|
||||
Fixture(const Fixture&) = delete;
|
||||
Fixture& operator=(const Fixture&) = delete;
|
||||
};
|
||||
|
||||
// Move-only callable that records every move: proves a rejected submission
|
||||
// never consumed it.
|
||||
struct TrackedCallable {
|
||||
std::shared_ptr<std::atomic<int>> moves{std::make_shared<std::atomic<int>>(0)};
|
||||
std::unique_ptr<int> payload{std::make_unique<int>(41)};
|
||||
std::atomic<bool>* ran{nullptr};
|
||||
|
||||
TrackedCallable() = default;
|
||||
explicit TrackedCallable(std::atomic<bool>* ran_flag) : ran(ran_flag) {}
|
||||
|
||||
TrackedCallable(TrackedCallable&& other) noexcept
|
||||
: moves(other.moves)
|
||||
, payload(std::move(other.payload))
|
||||
, ran(other.ran)
|
||||
{
|
||||
moves->fetch_add(1);
|
||||
}
|
||||
|
||||
TrackedCallable& operator=(TrackedCallable&&) = delete;
|
||||
TrackedCallable(const TrackedCallable&) = delete;
|
||||
TrackedCallable& operator=(const TrackedCallable&) = delete;
|
||||
|
||||
int operator()()
|
||||
{
|
||||
if (ran != nullptr) {
|
||||
ran->store(true);
|
||||
}
|
||||
return payload ? *payload + 1 : -1;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test future_pool_overloaded_does_not_consume_callable()
|
||||
{
|
||||
std::atomic<bool> blocker_running{false};
|
||||
std::atomic<bool> ran{false};
|
||||
Fixture fx{1, 1};
|
||||
FuturePool pool{*fx.exec};
|
||||
|
||||
auto blocker = pool.try_submit([&] {
|
||||
blocker_running.store(true);
|
||||
fx.gate.wait();
|
||||
return 7;
|
||||
});
|
||||
Void::Testing::require(blocker.has_value());
|
||||
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
|
||||
|
||||
TrackedCallable callable{&ran};
|
||||
const auto rejected = pool.try_submit(std::move(callable));
|
||||
Void::Testing::require(!rejected.has_value());
|
||||
Void::Testing::expect(rejected.error() == AdmissionError::overloaded);
|
||||
// Reserve-then-transfer: the callable was not even moved from.
|
||||
Void::Testing::expect_eq(callable.moves->load(), 0);
|
||||
Void::Testing::require(callable.payload != nullptr);
|
||||
Void::Testing::expect_eq(*callable.payload, 41);
|
||||
Void::Testing::expect(!ran.load());
|
||||
|
||||
fx.gate.open();
|
||||
Void::Testing::expect_eq(blocker->get(), 7);
|
||||
Void::Testing::require(wait_until([&] { return fx.exec->admitted() == 0; }));
|
||||
|
||||
// The very same callable is still usable.
|
||||
auto accepted = pool.try_submit(std::move(callable));
|
||||
Void::Testing::require(accepted.has_value());
|
||||
Void::Testing::expect_eq(accepted->get(), 42);
|
||||
Void::Testing::expect(ran.load());
|
||||
}
|
||||
|
||||
Void::Testing::Test future_pool_stopped_after_close()
|
||||
{
|
||||
Fixture fx{1, 4};
|
||||
FuturePool pool{*fx.exec};
|
||||
|
||||
auto before = pool.try_submit([] { return 1; });
|
||||
Void::Testing::require(before.has_value());
|
||||
Void::Testing::expect_eq(before->get(), 1);
|
||||
|
||||
fx.exec->close();
|
||||
std::atomic<bool> ran{false};
|
||||
TrackedCallable callable{&ran};
|
||||
const auto stopped = pool.try_submit(std::move(callable));
|
||||
Void::Testing::require(!stopped.has_value());
|
||||
Void::Testing::expect(stopped.error() == AdmissionError::stopped);
|
||||
Void::Testing::expect_eq(callable.moves->load(), 0);
|
||||
Void::Testing::expect(callable.payload != nullptr);
|
||||
Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{0});
|
||||
Void::Testing::require(fx.exec->join().has_value());
|
||||
Void::Testing::expect(!ran.load());
|
||||
}
|
||||
|
||||
Void::Testing::Test future_pool_exception_in_future()
|
||||
{
|
||||
Fixture fx{2, 8};
|
||||
FuturePool pool{*fx.exec};
|
||||
|
||||
auto failing = pool.try_submit([]() -> int { throw std::runtime_error{"boom"}; });
|
||||
Void::Testing::require(failing.has_value());
|
||||
bool caught = false;
|
||||
try {
|
||||
(void)failing->get();
|
||||
} catch (const std::runtime_error& error) {
|
||||
caught = std::string{error.what()} == "boom";
|
||||
}
|
||||
Void::Testing::expect(caught);
|
||||
|
||||
// void callables work, and a thrown exception does not poison the pool.
|
||||
std::atomic<int> ran{0};
|
||||
auto void_job = pool.try_submit([&ran] { ran.fetch_add(1); });
|
||||
Void::Testing::require(void_job.has_value());
|
||||
void_job->get();
|
||||
Void::Testing::expect_eq(ran.load(), 1);
|
||||
|
||||
auto after = pool.try_submit([] { return 5; });
|
||||
Void::Testing::require(after.has_value());
|
||||
Void::Testing::expect_eq(after->get(), 5);
|
||||
// Slots are released even when the callable threw.
|
||||
Void::Testing::expect(wait_until([&] { return fx.exec->admitted() == 0; }));
|
||||
}
|
||||
|
||||
Void::Testing::Test future_pool_bound_includes_running()
|
||||
{
|
||||
std::atomic<bool> first_running{false};
|
||||
std::atomic<int> started{0};
|
||||
Fixture fx{1, 2};
|
||||
FuturePool pool{*fx.exec};
|
||||
|
||||
auto running = pool.try_submit([&] {
|
||||
first_running.store(true);
|
||||
started.fetch_add(1);
|
||||
fx.gate.wait();
|
||||
return 1;
|
||||
});
|
||||
Void::Testing::require(running.has_value());
|
||||
Void::Testing::require(wait_until([&] { return first_running.load(); }));
|
||||
// The running callable still counts against the bound.
|
||||
Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{1});
|
||||
|
||||
auto queued = pool.try_submit([&] {
|
||||
started.fetch_add(1);
|
||||
return 2;
|
||||
});
|
||||
Void::Testing::require(queued.has_value());
|
||||
Void::Testing::expect_eq(fx.exec->admitted(), std::size_t{2});
|
||||
|
||||
const auto rejected = pool.try_submit([] { return 3; });
|
||||
Void::Testing::require(!rejected.has_value());
|
||||
Void::Testing::expect(rejected.error() == AdmissionError::overloaded);
|
||||
Void::Testing::expect_eq(fx.exec->stats().rejected, std::uint64_t{1});
|
||||
|
||||
fx.gate.open();
|
||||
Void::Testing::expect_eq(running->get(), 1);
|
||||
Void::Testing::expect_eq(queued->get(), 2);
|
||||
Void::Testing::expect_eq(started.load(), 2);
|
||||
Void::Testing::require(wait_until([&] { return fx.exec->admitted() == 0; }));
|
||||
|
||||
auto again = pool.try_submit([] { return 4; });
|
||||
Void::Testing::require(again.has_value());
|
||||
Void::Testing::expect_eq(again->get(), 4);
|
||||
}
|
||||
@@ -0,0 +1,626 @@
|
||||
#include <Void/Async/ParallelFor.hpp>
|
||||
#include <Void/Async/ThreadPool.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
#include <expected>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
// Assertions run on the test thread only (the assertion context is
|
||||
// thread_local); the loop bodies executed by pool workers only touch atomics or
|
||||
// distinct array elements.
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using namespace Void::Concurrency;
|
||||
using namespace std::chrono_literals;
|
||||
using Kind = ParallelForError::Kind;
|
||||
|
||||
class Gate
|
||||
{
|
||||
public:
|
||||
void open()
|
||||
{
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
open_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
}
|
||||
|
||||
void wait()
|
||||
{
|
||||
std::unique_lock lk{mu_};
|
||||
cv_.wait(lk, [this] { return open_; });
|
||||
}
|
||||
|
||||
private:
|
||||
std::mutex mu_{};
|
||||
std::condition_variable cv_{};
|
||||
bool open_{false};
|
||||
};
|
||||
|
||||
template <class Pred>
|
||||
bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms)
|
||||
{
|
||||
const auto end = std::chrono::steady_clock::now() + timeout;
|
||||
while (!pred()) {
|
||||
if (std::chrono::steady_clock::now() >= end) {
|
||||
return false;
|
||||
}
|
||||
std::this_thread::sleep_for(1ms);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Tracks the maximum number of concurrently running loop bodies.
|
||||
struct ConcurrencyMeter {
|
||||
std::atomic<int> active{0};
|
||||
std::atomic<int> peak{0};
|
||||
|
||||
void enter()
|
||||
{
|
||||
const int now = active.fetch_add(1) + 1;
|
||||
int seen = peak.load();
|
||||
while (now > seen && !peak.compare_exchange_weak(seen, now)) {
|
||||
}
|
||||
}
|
||||
|
||||
void leave() { active.fetch_sub(1); }
|
||||
};
|
||||
|
||||
std::string what(const std::exception_ptr& error)
|
||||
{
|
||||
if (!error) {
|
||||
return "<none>";
|
||||
}
|
||||
try {
|
||||
std::rethrow_exception(error);
|
||||
} catch (const std::exception& e) {
|
||||
return e.what();
|
||||
} catch (...) {
|
||||
return "<non-std>";
|
||||
}
|
||||
}
|
||||
|
||||
// Opens the gate on destruction so a failed assertion cannot leave a blocked
|
||||
// pool task hanging ~ThreadPool. Declare it AFTER the pool it protects.
|
||||
struct GateGuard {
|
||||
Gate& gate;
|
||||
~GateGuard() { gate.open(); }
|
||||
};
|
||||
|
||||
// Opens the gate and joins a helper thread on every exit path.
|
||||
struct ThreadJoiner {
|
||||
Gate& gate;
|
||||
std::thread& thread;
|
||||
~ThreadJoiner()
|
||||
{
|
||||
gate.open();
|
||||
if (thread.joinable()) {
|
||||
thread.join();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test parallel_for_bounded_grain_and_concurrency_limit()
|
||||
{
|
||||
constexpr int kCount = 40;
|
||||
ThreadPool pool{4};
|
||||
|
||||
// grain = 3 over [0, 40): 14 chunks, at most 2 running at once.
|
||||
{
|
||||
ConcurrencyMeter meter;
|
||||
std::vector<std::atomic<int>> hits(kCount);
|
||||
std::vector<std::thread::id> owner(kCount);
|
||||
std::vector<std::uint64_t> order(kCount, 0);
|
||||
std::atomic<std::uint64_t> sequence{0};
|
||||
const auto result = parallel_for(
|
||||
0, kCount,
|
||||
[&](int i) {
|
||||
meter.enter();
|
||||
owner[static_cast<std::size_t>(i)] = std::this_thread::get_id();
|
||||
order[static_cast<std::size_t>(i)] = sequence.fetch_add(1);
|
||||
hits[static_cast<std::size_t>(i)].fetch_add(1);
|
||||
std::this_thread::sleep_for(1ms);
|
||||
meter.leave();
|
||||
},
|
||||
pool, ParallelForOptions{.grain = 3, .max_concurrency = 2});
|
||||
Void::Testing::expect(result.has_value());
|
||||
int bad_hits = 0;
|
||||
int chunk_not_on_one_thread = 0;
|
||||
int chunk_not_ordered = 0;
|
||||
for (int i = 0; i < kCount; ++i) {
|
||||
if (hits[static_cast<std::size_t>(i)].load() != 1) {
|
||||
++bad_hits;
|
||||
}
|
||||
if (i % 3 != 0) {
|
||||
if (owner[static_cast<std::size_t>(i)] != owner[static_cast<std::size_t>(i - 1)]) {
|
||||
++chunk_not_on_one_thread;
|
||||
}
|
||||
if (order[static_cast<std::size_t>(i)] <= order[static_cast<std::size_t>(i - 1)]) {
|
||||
++chunk_not_ordered;
|
||||
}
|
||||
}
|
||||
}
|
||||
Void::Testing::expect_eq(bad_hits, 0);
|
||||
Void::Testing::expect_eq(chunk_not_on_one_thread, 0);
|
||||
Void::Testing::expect_eq(chunk_not_ordered, 0);
|
||||
Void::Testing::expect(meter.peak.load() >= 1);
|
||||
Void::Testing::expect(meter.peak.load() <= 2);
|
||||
}
|
||||
|
||||
// max_concurrency == 0 means the pool's thread count.
|
||||
{
|
||||
ConcurrencyMeter meter;
|
||||
std::atomic<int> calls{0};
|
||||
const auto result = parallel_for(
|
||||
0, 64,
|
||||
[&](int) {
|
||||
meter.enter();
|
||||
calls.fetch_add(1);
|
||||
std::this_thread::sleep_for(1ms);
|
||||
meter.leave();
|
||||
},
|
||||
pool, ParallelForOptions{});
|
||||
Void::Testing::expect(result.has_value());
|
||||
Void::Testing::expect_eq(calls.load(), 64);
|
||||
Void::Testing::expect(meter.peak.load() <= 4);
|
||||
}
|
||||
|
||||
// The error report carries the chunk geometry: 40 indices / grain 3 = 14.
|
||||
{
|
||||
std::atomic<int> calls{0};
|
||||
const auto result = parallel_for(
|
||||
0, kCount,
|
||||
[&](int i) {
|
||||
calls.fetch_add(1);
|
||||
if (i == 7) {
|
||||
throw std::runtime_error{"seven"};
|
||||
}
|
||||
},
|
||||
pool, ParallelForOptions{.grain = 3, .max_concurrency = 2, .stop_on_error = false});
|
||||
Void::Testing::require(!result.has_value());
|
||||
Void::Testing::expect(result.error().kind == Kind::failed);
|
||||
Void::Testing::expect_eq(result.error().chunks_total, std::size_t{14});
|
||||
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{14});
|
||||
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{1});
|
||||
Void::Testing::expect(result.error().first_failed_chunk == std::optional<std::size_t>{2});
|
||||
Void::Testing::expect_eq(what(result.error().first_exception), std::string{"seven"});
|
||||
// The throwing chunk [6, 9) stops at index 7; every other chunk ran fully.
|
||||
Void::Testing::expect_eq(calls.load(), kCount - 1);
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test parallel_for_bounded_signed_and_unsigned_ranges()
|
||||
{
|
||||
ThreadPool pool{3};
|
||||
|
||||
// Signed range crossing zero.
|
||||
{
|
||||
std::atomic<int> sum{0};
|
||||
std::atomic<int> calls{0};
|
||||
const auto result = parallel_for(
|
||||
-5, 5, [&](int i) { sum.fetch_add(i); calls.fetch_add(1); }, pool,
|
||||
ParallelForOptions{.grain = 4});
|
||||
Void::Testing::expect(result.has_value());
|
||||
Void::Testing::expect_eq(calls.load(), 10);
|
||||
Void::Testing::expect_eq(sum.load(), -5);
|
||||
}
|
||||
|
||||
// The whole int8 range: 255 indices computed in the unsigned type.
|
||||
{
|
||||
std::vector<std::atomic<int>> hits(256);
|
||||
const auto result = parallel_for(
|
||||
std::int8_t{-128}, std::int8_t{127},
|
||||
[&](std::int8_t i) { hits[static_cast<std::size_t>(i + 128)].fetch_add(1); }, pool,
|
||||
ParallelForOptions{.grain = 7});
|
||||
Void::Testing::expect(result.has_value());
|
||||
int wrong = 0;
|
||||
for (std::size_t k = 0; k < 255; ++k) {
|
||||
if (hits[k].load() != 1) {
|
||||
++wrong;
|
||||
}
|
||||
}
|
||||
Void::Testing::expect_eq(wrong, 0);
|
||||
Void::Testing::expect_eq(hits[255].load(), 0);
|
||||
}
|
||||
|
||||
// Top of the unsigned range, and a grain larger than the range.
|
||||
{
|
||||
std::atomic<int> calls{0};
|
||||
std::atomic<std::uint64_t> sum{0};
|
||||
const std::uint64_t top = std::numeric_limits<std::uint64_t>::max();
|
||||
const auto result = parallel_for(
|
||||
top - 3, top, [&](std::uint64_t i) { calls.fetch_add(1); sum.fetch_add(top - i); }, pool,
|
||||
ParallelForOptions{.grain = 1000});
|
||||
Void::Testing::expect(result.has_value());
|
||||
Void::Testing::expect_eq(calls.load(), 3);
|
||||
Void::Testing::expect_eq(sum.load(), std::uint64_t{3 + 2 + 1});
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test parallel_for_bounded_stop_joins_started_no_new_chunks()
|
||||
{
|
||||
ThreadPool pool{2};
|
||||
|
||||
// One runner: chunk 0 requests stop; no later chunk may start.
|
||||
{
|
||||
std::stop_source stop;
|
||||
std::atomic<int> started{0};
|
||||
std::atomic<int> finished{0};
|
||||
const auto result = parallel_for(
|
||||
0, 100,
|
||||
[&](int i) {
|
||||
started.fetch_add(1);
|
||||
if (i == 0) {
|
||||
stop.request_stop();
|
||||
std::this_thread::sleep_for(5ms);
|
||||
}
|
||||
finished.fetch_add(1);
|
||||
},
|
||||
pool, ParallelForOptions{.grain = 1, .max_concurrency = 1, .stop = stop.get_token()});
|
||||
Void::Testing::require(!result.has_value());
|
||||
Void::Testing::expect(result.error().kind == Kind::stopped);
|
||||
Void::Testing::expect_eq(result.error().chunks_total, std::size_t{100});
|
||||
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{1});
|
||||
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{0});
|
||||
Void::Testing::expect(!result.error().first_failed_chunk.has_value());
|
||||
// The started chunk was joined (ran to completion) and nothing else ran.
|
||||
Void::Testing::expect_eq(started.load(), 1);
|
||||
Void::Testing::expect_eq(finished.load(), 1);
|
||||
}
|
||||
|
||||
// Two runners: every chunk that started finishes; the rest never start.
|
||||
{
|
||||
std::stop_source stop;
|
||||
std::atomic<int> started{0};
|
||||
std::atomic<int> finished{0};
|
||||
const auto result = parallel_for(
|
||||
0, 1000,
|
||||
[&](int i) {
|
||||
started.fetch_add(1);
|
||||
if (i == 3) {
|
||||
stop.request_stop();
|
||||
}
|
||||
std::this_thread::sleep_for(1ms);
|
||||
finished.fetch_add(1);
|
||||
},
|
||||
pool, ParallelForOptions{.grain = 1, .max_concurrency = 2, .stop = stop.get_token()});
|
||||
Void::Testing::require(!result.has_value());
|
||||
Void::Testing::expect(result.error().kind == Kind::stopped);
|
||||
Void::Testing::expect_eq(started.load(), finished.load());
|
||||
Void::Testing::expect_eq(result.error().chunks_started, static_cast<std::size_t>(started.load()));
|
||||
Void::Testing::expect(result.error().chunks_started < std::size_t{1000});
|
||||
Void::Testing::expect(result.error().chunks_started >= std::size_t{4});
|
||||
}
|
||||
|
||||
// Stop requested before the call: nothing runs.
|
||||
{
|
||||
std::stop_source stop;
|
||||
stop.request_stop();
|
||||
std::atomic<int> calls{0};
|
||||
const auto result = parallel_for(
|
||||
0, 10, [&](int) { calls.fetch_add(1); }, pool,
|
||||
ParallelForOptions{.stop = stop.get_token()});
|
||||
Void::Testing::require(!result.has_value());
|
||||
Void::Testing::expect(result.error().kind == Kind::stopped);
|
||||
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{0});
|
||||
Void::Testing::expect_eq(result.error().chunks_total, std::size_t{10});
|
||||
Void::Testing::expect_eq(calls.load(), 0);
|
||||
}
|
||||
|
||||
// A stop that arrives once every chunk has started is not an error.
|
||||
{
|
||||
std::stop_source stop;
|
||||
std::atomic<int> calls{0};
|
||||
const auto result = parallel_for(
|
||||
0, 4,
|
||||
[&](int i) {
|
||||
calls.fetch_add(1);
|
||||
if (i == 3) {
|
||||
stop.request_stop();
|
||||
}
|
||||
},
|
||||
pool, ParallelForOptions{.max_concurrency = 1, .stop = stop.get_token()});
|
||||
Void::Testing::expect(result.has_value());
|
||||
Void::Testing::expect_eq(calls.load(), 4);
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test parallel_for_bounded_errors_join_all_lowest_index_reported()
|
||||
{
|
||||
ThreadPool pool{2};
|
||||
|
||||
// stop_on_error == false: every chunk runs; the lowest failed chunk wins
|
||||
// even though higher chunks fail first or concurrently.
|
||||
{
|
||||
std::atomic<int> calls{0};
|
||||
const auto result = parallel_for(
|
||||
0, 10,
|
||||
[&](int i) {
|
||||
calls.fetch_add(1);
|
||||
if (i == 5 || i == 2 || i == 8) {
|
||||
throw std::runtime_error{"chunk " + std::to_string(i)};
|
||||
}
|
||||
},
|
||||
pool, ParallelForOptions{.grain = 1, .max_concurrency = 2, .stop_on_error = false});
|
||||
Void::Testing::require(!result.has_value());
|
||||
Void::Testing::expect(result.error().kind == Kind::failed);
|
||||
Void::Testing::expect_eq(calls.load(), 10);
|
||||
Void::Testing::expect_eq(result.error().chunks_total, std::size_t{10});
|
||||
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{10});
|
||||
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{3});
|
||||
Void::Testing::expect(result.error().first_failed_chunk == std::optional<std::size_t>{2});
|
||||
Void::Testing::expect_eq(what(result.error().first_exception), std::string{"chunk 2"});
|
||||
}
|
||||
|
||||
// stop_on_error == true: chunk 1 fails first, chunk 0 (already started)
|
||||
// fails afterwards. The caller joins both and reports the LOWER chunk; no
|
||||
// new chunk starts after the first failure.
|
||||
{
|
||||
std::atomic<bool> chunk_one_failed{false};
|
||||
std::atomic<bool> chunk_zero_timed_out{false};
|
||||
std::atomic<int> calls{0};
|
||||
const auto result = parallel_for(
|
||||
0, 10,
|
||||
[&](int i) {
|
||||
calls.fetch_add(1);
|
||||
if (i == 0) {
|
||||
const auto end = std::chrono::steady_clock::now() + 5s;
|
||||
while (!chunk_one_failed.load() && std::chrono::steady_clock::now() < end) {
|
||||
std::this_thread::yield();
|
||||
}
|
||||
if (!chunk_one_failed.load()) {
|
||||
chunk_zero_timed_out.store(true);
|
||||
}
|
||||
throw std::runtime_error{"zero"};
|
||||
}
|
||||
if (i == 1) {
|
||||
chunk_one_failed.store(true);
|
||||
throw std::runtime_error{"one"};
|
||||
}
|
||||
},
|
||||
pool, ParallelForOptions{.grain = 1, .max_concurrency = 2, .stop_on_error = true});
|
||||
Void::Testing::require(!result.has_value());
|
||||
Void::Testing::expect(!chunk_zero_timed_out.load());
|
||||
Void::Testing::expect(result.error().kind == Kind::failed);
|
||||
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{2});
|
||||
Void::Testing::expect(result.error().first_failed_chunk == std::optional<std::size_t>{0});
|
||||
Void::Testing::expect_eq(what(result.error().first_exception), std::string{"zero"});
|
||||
// Only the two started chunks ran.
|
||||
Void::Testing::expect_eq(result.error().chunks_started, std::size_t{2});
|
||||
Void::Testing::expect_eq(calls.load(), 2);
|
||||
}
|
||||
|
||||
// `failed` outranks `stopped`.
|
||||
{
|
||||
std::stop_source stop;
|
||||
const auto result = parallel_for(
|
||||
0, 10,
|
||||
[&](int i) {
|
||||
if (i == 0) {
|
||||
stop.request_stop();
|
||||
throw std::runtime_error{"failed and stopped"};
|
||||
}
|
||||
},
|
||||
pool, ParallelForOptions{.grain = 1, .max_concurrency = 1, .stop = stop.get_token()});
|
||||
Void::Testing::require(!result.has_value());
|
||||
Void::Testing::expect(result.error().kind == Kind::failed);
|
||||
Void::Testing::expect_eq(result.error().chunks_failed, std::size_t{1});
|
||||
}
|
||||
|
||||
// A non-std exception is preserved as an exception_ptr.
|
||||
{
|
||||
const auto result = parallel_for(
|
||||
0, 3, [](int i) { if (i == 1) { throw 42; } }, pool,
|
||||
ParallelForOptions{.grain = 1, .max_concurrency = 1, .stop_on_error = false});
|
||||
Void::Testing::require(!result.has_value());
|
||||
bool is_int = false;
|
||||
try {
|
||||
std::rethrow_exception(result.error().first_exception);
|
||||
} catch (int value) {
|
||||
is_int = value == 42;
|
||||
} catch (...) {
|
||||
}
|
||||
Void::Testing::expect(is_int);
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test parallel_for_bounded_zero_grain_invalid()
|
||||
{
|
||||
ThreadPool pool{2};
|
||||
std::atomic<int> calls{0};
|
||||
|
||||
const auto zero_grain = parallel_for(
|
||||
0, 10, [&](int) { calls.fetch_add(1); }, pool, ParallelForOptions{.grain = 0});
|
||||
Void::Testing::require(!zero_grain.has_value());
|
||||
Void::Testing::expect(zero_grain.error().kind == Kind::invalid_argument);
|
||||
Void::Testing::expect_eq(zero_grain.error().chunks_total, std::size_t{0});
|
||||
Void::Testing::expect_eq(zero_grain.error().chunks_started, std::size_t{0});
|
||||
Void::Testing::expect_eq(calls.load(), 0);
|
||||
|
||||
// An empty or reversed range is a success and runs nothing.
|
||||
const auto empty = parallel_for(5, 5, [&](int) { calls.fetch_add(1); }, pool, ParallelForOptions{});
|
||||
Void::Testing::expect(empty.has_value());
|
||||
const auto reversed = parallel_for(9, 2, [&](int) { calls.fetch_add(1); }, pool, ParallelForOptions{});
|
||||
Void::Testing::expect(reversed.has_value());
|
||||
Void::Testing::expect_eq(calls.load(), 0);
|
||||
|
||||
// The legacy overloads are unchanged.
|
||||
std::atomic<int> legacy{0};
|
||||
parallel_for(0, 5, [&](int) { legacy.fetch_add(1); }, pool);
|
||||
Void::Testing::expect_eq(legacy.load(), 5);
|
||||
}
|
||||
|
||||
Void::Testing::Test parallel_for_bounded_rejected_pool_runs_inline()
|
||||
{
|
||||
Gate gate;
|
||||
std::atomic<bool> blocker_started{false};
|
||||
{
|
||||
// One worker, queue bound 1: occupy the worker and fill the queue so
|
||||
// every try_submit is rejected.
|
||||
ThreadPool pool{1, 1};
|
||||
GateGuard guard{gate};
|
||||
auto blocker = pool.submit([&] {
|
||||
blocker_started.store(true);
|
||||
gate.wait();
|
||||
});
|
||||
Void::Testing::require(wait_until([&] { return blocker_started.load(); }));
|
||||
auto filler = pool.submit([] {});
|
||||
Void::Testing::expect_eq(pool.pending_count(), std::size_t{1});
|
||||
|
||||
std::vector<std::thread::id> owner(20);
|
||||
std::atomic<int> calls{0};
|
||||
const auto caller = std::this_thread::get_id();
|
||||
const auto result = parallel_for(
|
||||
0, 20,
|
||||
[&](int i) {
|
||||
owner[static_cast<std::size_t>(i)] = std::this_thread::get_id();
|
||||
calls.fetch_add(1);
|
||||
},
|
||||
pool, ParallelForOptions{.grain = 4, .max_concurrency = 3});
|
||||
Void::Testing::expect(result.has_value());
|
||||
Void::Testing::expect_eq(calls.load(), 20);
|
||||
int off_caller = 0;
|
||||
for (const auto& id : owner) {
|
||||
if (id != caller) {
|
||||
++off_caller;
|
||||
}
|
||||
}
|
||||
// The pool rejected the runner, so the calling thread ran everything.
|
||||
Void::Testing::expect_eq(off_caller, 0);
|
||||
Void::Testing::expect(pool.stats().rejected >= 1);
|
||||
|
||||
gate.open();
|
||||
blocker.get();
|
||||
filler.get();
|
||||
}
|
||||
|
||||
// Partial rejection: the caller joins the accepted runner but the bound
|
||||
// on running chunks still holds (accepted runners + the caller).
|
||||
{
|
||||
ThreadPool pool{1, 1};
|
||||
ConcurrencyMeter meter;
|
||||
std::vector<std::atomic<int>> hits(30);
|
||||
const auto result = parallel_for(
|
||||
0, 30,
|
||||
[&](int i) {
|
||||
meter.enter();
|
||||
hits[static_cast<std::size_t>(i)].fetch_add(1);
|
||||
std::this_thread::sleep_for(1ms);
|
||||
meter.leave();
|
||||
},
|
||||
pool, ParallelForOptions{.grain = 1, .max_concurrency = 2});
|
||||
Void::Testing::expect(result.has_value());
|
||||
int wrong = 0;
|
||||
for (const auto& hit : hits) {
|
||||
if (hit.load() != 1) {
|
||||
++wrong;
|
||||
}
|
||||
}
|
||||
Void::Testing::expect_eq(wrong, 0);
|
||||
Void::Testing::expect(meter.peak.load() <= 2);
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test parallel_for_bounded_waits_all_submitted_runners()
|
||||
{
|
||||
Gate gate;
|
||||
std::atomic<bool> blocker_started{false};
|
||||
std::atomic<bool> returned{false};
|
||||
std::atomic<int> calls{0};
|
||||
std::optional<std::expected<void, ParallelForError>> outcome;
|
||||
std::stop_source stop;
|
||||
|
||||
ThreadPool pool{1};
|
||||
GateGuard guard{gate};
|
||||
auto blocker = pool.submit([&] {
|
||||
blocker_started.store(true);
|
||||
gate.wait();
|
||||
});
|
||||
Void::Testing::require(wait_until([&] { return blocker_started.load(); }));
|
||||
|
||||
// Three runners queue behind the blocker and cannot start. The caller must
|
||||
// still wait for every one of them, also after a stop was requested.
|
||||
std::thread caller([&] {
|
||||
outcome = parallel_for(
|
||||
0, 100, [&](int) { calls.fetch_add(1); }, pool,
|
||||
ParallelForOptions{.grain = 10, .max_concurrency = 3, .stop = stop.get_token()});
|
||||
returned.store(true);
|
||||
});
|
||||
ThreadJoiner joiner{gate, caller};
|
||||
Void::Testing::expect(wait_until([&] { return pool.pending_count() == 3; }));
|
||||
stop.request_stop();
|
||||
std::this_thread::sleep_for(60ms);
|
||||
Void::Testing::expect(!returned.load());
|
||||
|
||||
gate.open();
|
||||
caller.join();
|
||||
blocker.get();
|
||||
Void::Testing::expect(returned.load());
|
||||
Void::Testing::require(outcome.has_value());
|
||||
Void::Testing::require(!outcome->has_value());
|
||||
Void::Testing::expect((*outcome).error().kind == Kind::stopped);
|
||||
// The runners found the stop request: no chunk ever started.
|
||||
Void::Testing::expect_eq((*outcome).error().chunks_started, std::size_t{0});
|
||||
Void::Testing::expect_eq((*outcome).error().chunks_total, std::size_t{10});
|
||||
Void::Testing::expect_eq(calls.load(), 0);
|
||||
// Every runner future was waited for: the queue is empty.
|
||||
Void::Testing::expect_eq(pool.pending_count(), std::size_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test legacy_parallel_for_exception_joins_all()
|
||||
{
|
||||
ThreadPool pool{2};
|
||||
std::atomic<int> finished{0};
|
||||
bool caught = false;
|
||||
try {
|
||||
parallel_for(0, 8, [&](int i) {
|
||||
if (i == 0) {
|
||||
throw std::runtime_error{"first"};
|
||||
}
|
||||
std::this_thread::sleep_for(25ms);
|
||||
finished.fetch_add(1);
|
||||
}, pool);
|
||||
} catch (const std::runtime_error& error) {
|
||||
caught = std::string{error.what()} == "first";
|
||||
}
|
||||
Void::Testing::expect(caught);
|
||||
// The exception surfaced only after every other task finished; none is
|
||||
// still running against this stack.
|
||||
Void::Testing::expect_eq(finished.load(), 7);
|
||||
|
||||
// With several failures the first (lowest index) is rethrown.
|
||||
std::atomic<int> second_finished{0};
|
||||
std::string message;
|
||||
try {
|
||||
parallel_for(0, 6, [&](int i) {
|
||||
std::this_thread::sleep_for(5ms);
|
||||
second_finished.fetch_add(1);
|
||||
if (i == 1 || i == 3) {
|
||||
throw std::runtime_error{"error " + std::to_string(i)};
|
||||
}
|
||||
}, pool);
|
||||
} catch (const std::runtime_error& error) {
|
||||
message = error.what();
|
||||
}
|
||||
Void::Testing::expect_eq(message, std::string{"error 1"});
|
||||
Void::Testing::expect_eq(second_finished.load(), 6);
|
||||
}
|
||||
@@ -0,0 +1,881 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/TaskScope.hpp>
|
||||
#include <Void/Async/ThreadExecutor.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <coroutine>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
// Every assertion runs on the test thread: jobs executed by workers only touch
|
||||
// atomics or mutex-guarded containers (the assertion context is thread_local).
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using namespace Void::Async;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
// Detached, self-destroying coroutine frame created suspended: a handle to
|
||||
// post. A job that is never resumed must be destroy()ed by its creator.
|
||||
struct Job {
|
||||
struct promise_type {
|
||||
Job get_return_object() noexcept
|
||||
{
|
||||
return Job{std::coroutine_handle<promise_type>::from_promise(*this)};
|
||||
}
|
||||
std::suspend_always initial_suspend() noexcept { return {}; }
|
||||
std::suspend_never final_suspend() noexcept { return {}; }
|
||||
void return_void() noexcept {}
|
||||
void unhandled_exception() noexcept { std::terminate(); }
|
||||
};
|
||||
|
||||
std::coroutine_handle<promise_type> handle{};
|
||||
};
|
||||
|
||||
Job make_job(std::function<void()> body)
|
||||
{
|
||||
body();
|
||||
co_return;
|
||||
}
|
||||
|
||||
class Gate
|
||||
{
|
||||
public:
|
||||
void open()
|
||||
{
|
||||
{
|
||||
std::lock_guard lk{mu_};
|
||||
open_ = true;
|
||||
}
|
||||
cv_.notify_all();
|
||||
}
|
||||
|
||||
void wait()
|
||||
{
|
||||
std::unique_lock lk{mu_};
|
||||
cv_.wait(lk, [this] { return open_; });
|
||||
}
|
||||
|
||||
private:
|
||||
std::mutex mu_{};
|
||||
std::condition_variable cv_{};
|
||||
bool open_{false};
|
||||
};
|
||||
|
||||
template <class Pred>
|
||||
bool wait_until(Pred pred, std::chrono::milliseconds timeout = 5000ms)
|
||||
{
|
||||
const auto end = std::chrono::steady_clock::now() + timeout;
|
||||
while (!pred()) {
|
||||
if (std::chrono::steady_clock::now() >= end) {
|
||||
return false;
|
||||
}
|
||||
std::this_thread::sleep_for(1ms);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Owns the executor and a gate. The destructor opens the gate FIRST, so a
|
||||
// failed assertion can never leave a blocker job hanging ~ThreadExecutor, then
|
||||
// destroys the executor (which joins) and finally the gate.
|
||||
struct Fixture {
|
||||
Gate gate{};
|
||||
std::unique_ptr<ThreadExecutor> exec{};
|
||||
|
||||
Fixture(std::size_t workers, std::size_t max_admitted, bool start = true)
|
||||
{
|
||||
auto created = ThreadExecutor::create(
|
||||
ThreadExecutorOptions{.workers = workers, .max_admitted = max_admitted});
|
||||
Void::Testing::require(created.has_value());
|
||||
exec = std::move(*created);
|
||||
if (start) {
|
||||
Void::Testing::require(exec->start().has_value());
|
||||
}
|
||||
}
|
||||
|
||||
~Fixture() { gate.open(); }
|
||||
|
||||
Fixture(const Fixture&) = delete;
|
||||
Fixture& operator=(const Fixture&) = delete;
|
||||
|
||||
ThreadExecutor& operator*() { return *exec; }
|
||||
ThreadExecutor* operator->() { return exec.get(); }
|
||||
};
|
||||
|
||||
// A job that occupies a worker until the fixture gate opens.
|
||||
Job make_blocker(Fixture& fx, std::atomic<bool>& running)
|
||||
{
|
||||
return make_job([&fx, &running] {
|
||||
running.store(true, std::memory_order_release);
|
||||
fx.gate.wait();
|
||||
});
|
||||
}
|
||||
|
||||
std::optional<AsyncErrorCode> async_code(const Void::Result::Error& error)
|
||||
{
|
||||
if (error.code().domain != Void::Result::kAsyncErrorDomain) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<AsyncErrorCode>(error.code().value);
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> bump_task(std::atomic<int>* counter)
|
||||
{
|
||||
counter->fetch_add(1, std::memory_order_relaxed);
|
||||
co_return;
|
||||
}
|
||||
|
||||
// Posts `job` through one of the four admission paths (retrying while the
|
||||
// bound is full). Returns false (and destroys the frame) on an unexpected
|
||||
// rejection. Assertion free: runs on poster threads.
|
||||
bool post_one(ThreadExecutor& exec, int kind, Job& job)
|
||||
{
|
||||
switch (kind) {
|
||||
case 0:
|
||||
for (;;) {
|
||||
const auto admitted = exec.try_post(job.handle);
|
||||
if (admitted.has_value()) {
|
||||
return true;
|
||||
}
|
||||
if (admitted.error() != AdmissionError::overloaded) {
|
||||
job.handle.destroy();
|
||||
return false;
|
||||
}
|
||||
std::this_thread::yield();
|
||||
}
|
||||
case 1:
|
||||
exec.post(job.handle);
|
||||
return true;
|
||||
case 2:
|
||||
exec.post_completion(job.handle);
|
||||
return true;
|
||||
default:
|
||||
for (;;) {
|
||||
const auto reserved = exec.try_reserve_slot();
|
||||
if (reserved.has_value()) {
|
||||
break;
|
||||
}
|
||||
if (reserved.error() != AdmissionError::overloaded) {
|
||||
job.handle.destroy();
|
||||
return false;
|
||||
}
|
||||
std::this_thread::yield();
|
||||
}
|
||||
exec.commit_reserved(job.handle);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test thread_executor_create_starts_no_threads()
|
||||
{
|
||||
std::atomic<int> hook_calls{0};
|
||||
std::atomic<int> ran{0};
|
||||
auto created = ThreadExecutor::create(ThreadExecutorOptions{
|
||||
.workers = 2,
|
||||
.max_admitted = 4,
|
||||
.before_worker_start = [&hook_calls](std::size_t) -> Void::Result::Result<void> {
|
||||
hook_calls.fetch_add(1);
|
||||
return {};
|
||||
}});
|
||||
Void::Testing::require(created.has_value());
|
||||
auto& exec = **created;
|
||||
|
||||
// No thread (and no hook call) exists yet.
|
||||
Void::Testing::expect_eq(hook_calls.load(), 0);
|
||||
Void::Testing::expect(exec.idle());
|
||||
Void::Testing::expect_eq(exec.admitted(), std::size_t{0});
|
||||
Void::Testing::expect(exec.supports_reservation());
|
||||
Void::Testing::expect(exec.has_background_workers());
|
||||
|
||||
// Admission before start() queues normally and nothing runs.
|
||||
auto job = make_job([&ran] { ran.fetch_add(1); });
|
||||
Void::Testing::require(exec.try_post(job.handle).has_value());
|
||||
Void::Testing::expect_eq(exec.admitted(), std::size_t{1});
|
||||
std::this_thread::sleep_for(30ms);
|
||||
Void::Testing::expect_eq(ran.load(), 0);
|
||||
Void::Testing::expect_eq(exec.stats().queued, std::size_t{1});
|
||||
Void::Testing::expect(!exec.idle());
|
||||
|
||||
Void::Testing::require(exec.start().has_value());
|
||||
Void::Testing::expect_eq(hook_calls.load(), 2);
|
||||
Void::Testing::expect(wait_until([&] { return ran.load() == 1; }));
|
||||
Void::Testing::require(exec.join().has_value());
|
||||
|
||||
// create() validates its options.
|
||||
const auto zero_workers = ThreadExecutor::create(ThreadExecutorOptions{.workers = 0});
|
||||
Void::Testing::require(!zero_workers.has_value());
|
||||
Void::Testing::expect(async_code(zero_workers.error()) == AsyncErrorCode::invalid_argument);
|
||||
const auto zero_bound = ThreadExecutor::create(ThreadExecutorOptions{.max_admitted = 0});
|
||||
Void::Testing::require(!zero_bound.has_value());
|
||||
Void::Testing::expect(async_code(zero_bound.error()) == AsyncErrorCode::invalid_argument);
|
||||
}
|
||||
|
||||
Void::Testing::Test thread_executor_bound_includes_running_work()
|
||||
{
|
||||
std::atomic<bool> blocker_running{false};
|
||||
std::atomic<int> ran{0};
|
||||
Fixture exec{1, 2};
|
||||
|
||||
auto blocker = make_blocker(exec, blocker_running);
|
||||
Void::Testing::require(exec->try_post(blocker.handle).has_value());
|
||||
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
|
||||
// The running blocker keeps its slot.
|
||||
Void::Testing::expect_eq(exec->admitted(), std::size_t{1});
|
||||
Void::Testing::expect_eq(exec->stats().running, std::size_t{1});
|
||||
|
||||
auto queued = make_job([&ran] { ran.fetch_add(1); });
|
||||
Void::Testing::require(exec->try_post(queued.handle).has_value());
|
||||
Void::Testing::expect_eq(exec->admitted(), std::size_t{2});
|
||||
|
||||
// running (1) + queued (1) == max_admitted (2): the next one is rejected.
|
||||
auto rejected = make_job([&ran] { ran.fetch_add(100); });
|
||||
const auto overloaded = exec->try_post(rejected.handle);
|
||||
Void::Testing::expect(!overloaded.has_value());
|
||||
Void::Testing::expect(overloaded.error() == AdmissionError::overloaded);
|
||||
rejected.handle.destroy();
|
||||
Void::Testing::expect_eq(exec->stats().rejected, std::uint64_t{1});
|
||||
Void::Testing::expect_eq(exec->stats().queued, std::size_t{1});
|
||||
|
||||
// Legacy post() never rejects: it may exceed the bound and is counted.
|
||||
auto legacy = make_job([&ran] { ran.fetch_add(10); });
|
||||
exec->post(legacy.handle);
|
||||
Void::Testing::expect_eq(exec->admitted(), std::size_t{3});
|
||||
Void::Testing::expect_eq(exec->stats().legacy_posts, std::uint64_t{1});
|
||||
|
||||
// A null handle is invalid for try_post.
|
||||
const auto null_handle = exec->try_post({});
|
||||
Void::Testing::expect(!null_handle.has_value());
|
||||
Void::Testing::expect(null_handle.error() == AdmissionError::invalid_argument);
|
||||
|
||||
exec.gate.open();
|
||||
Void::Testing::expect(wait_until([&] { return ran.load() == 11 && exec->idle(); }));
|
||||
// A slot is free again once the work returned.
|
||||
auto again = make_job([&ran] { ran.fetch_add(1000); });
|
||||
Void::Testing::require(exec->try_post(again.handle).has_value());
|
||||
Void::Testing::expect(wait_until([&] { return ran.load() == 1011; }));
|
||||
Void::Testing::expect(wait_until([&] { return exec->admitted() == 0; }));
|
||||
}
|
||||
|
||||
Void::Testing::Test thread_executor_reservation_with_task_scope_preserves_task()
|
||||
{
|
||||
std::atomic<bool> blocker_running{false};
|
||||
std::atomic<int> ran{0};
|
||||
Fixture exec{1, 1};
|
||||
TaskScope scope{*exec, TaskScopeOptions{.max_tasks = 8}};
|
||||
|
||||
auto blocker = make_blocker(exec, blocker_running);
|
||||
Void::Testing::require(exec->try_post(blocker.handle).has_value());
|
||||
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
|
||||
|
||||
// The bound is full: TaskScope's reserve-then-transfer is rejected and the
|
||||
// caller still owns the task.
|
||||
auto preserved = bump_task(&ran);
|
||||
const auto rejected = scope.spawn(std::move(preserved));
|
||||
Void::Testing::require(!rejected.has_value());
|
||||
Void::Testing::expect(rejected.error() == AdmissionError::overloaded);
|
||||
Void::Testing::expect(static_cast<bool>(preserved.handle()));
|
||||
Void::Testing::expect(!preserved.done());
|
||||
// The failed reservation did not leak a slot.
|
||||
Void::Testing::expect_eq(exec->admitted(), std::size_t{1});
|
||||
Void::Testing::expect_eq(ran.load(), 0);
|
||||
|
||||
exec.gate.open();
|
||||
Void::Testing::require(wait_until([&] { return exec->admitted() == 0; }));
|
||||
const auto accepted = scope.spawn(std::move(preserved));
|
||||
Void::Testing::require(accepted.has_value());
|
||||
Void::Testing::require(scope.join_blocking().has_value());
|
||||
Void::Testing::expect_eq(ran.load(), 1);
|
||||
Void::Testing::expect(wait_until([&] { return exec->admitted() == 0; }));
|
||||
}
|
||||
|
||||
Void::Testing::Test thread_executor_completion_lane_bypasses_full_normal_lane()
|
||||
{
|
||||
std::atomic<bool> blocker_running{false};
|
||||
std::atomic<int> completion_ran{0};
|
||||
Fixture exec{1, 1};
|
||||
|
||||
auto blocker = make_blocker(exec, blocker_running);
|
||||
Void::Testing::require(exec->try_post(blocker.handle).has_value());
|
||||
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
|
||||
|
||||
// The normal lane is full ...
|
||||
auto normal = make_job([] {});
|
||||
const auto overloaded = exec->try_post(normal.handle);
|
||||
Void::Testing::expect(!overloaded.has_value());
|
||||
normal.handle.destroy();
|
||||
const auto reserve_rejected = exec->try_reserve_slot();
|
||||
Void::Testing::expect(!reserve_rejected.has_value());
|
||||
Void::Testing::expect(reserve_rejected.error() == AdmissionError::overloaded);
|
||||
|
||||
// ... but the completion lane still accepts and is not part of the bound.
|
||||
auto completion = make_job([&completion_ran] { completion_ran.fetch_add(1); });
|
||||
exec->post_completion(completion.handle);
|
||||
Void::Testing::expect_eq(exec->stats().completion_queued, std::size_t{1});
|
||||
Void::Testing::expect_eq(exec->admitted(), std::size_t{1});
|
||||
|
||||
exec.gate.open();
|
||||
Void::Testing::expect(wait_until([&] { return completion_ran.load() == 1; }));
|
||||
Void::Testing::expect(wait_until([&] { return exec->idle(); }));
|
||||
}
|
||||
|
||||
Void::Testing::Test thread_executor_close_rejects_normal_drains_completion()
|
||||
{
|
||||
std::atomic<bool> blocker_running{false};
|
||||
std::atomic<int> order_counter{0};
|
||||
std::atomic<int> completion_order{-1};
|
||||
std::atomic<int> legacy_order{-1};
|
||||
std::atomic<int> queued_order{-1};
|
||||
Fixture exec{1, 8};
|
||||
|
||||
auto blocker = make_blocker(exec, blocker_running);
|
||||
Void::Testing::require(exec->try_post(blocker.handle).has_value());
|
||||
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
|
||||
|
||||
auto queued = make_job([&] { queued_order.store(order_counter.fetch_add(1)); });
|
||||
Void::Testing::require(exec->try_post(queued.handle).has_value());
|
||||
|
||||
exec->close();
|
||||
|
||||
// Normal admission is closed.
|
||||
auto refused = make_job([] {});
|
||||
const auto stopped_post = exec->try_post(refused.handle);
|
||||
Void::Testing::expect(!stopped_post.has_value());
|
||||
Void::Testing::expect(stopped_post.error() == AdmissionError::stopped);
|
||||
refused.handle.destroy();
|
||||
const auto stopped_reserve = exec->try_reserve_slot();
|
||||
Void::Testing::expect(!stopped_reserve.has_value());
|
||||
Void::Testing::expect(stopped_reserve.error() == AdmissionError::stopped);
|
||||
|
||||
// A legacy post after close() is redirected to the completion lane and
|
||||
// counted; post_completion keeps working.
|
||||
auto legacy = make_job([&] { legacy_order.store(order_counter.fetch_add(1)); });
|
||||
exec->post(legacy.handle);
|
||||
auto completion = make_job([&] { completion_order.store(order_counter.fetch_add(1)); });
|
||||
exec->post_completion(completion.handle);
|
||||
Void::Testing::expect_eq(exec->stats().completion_queued, std::size_t{2});
|
||||
Void::Testing::expect_eq(exec->stats().legacy_posts, std::uint64_t{1});
|
||||
|
||||
exec.gate.open();
|
||||
Void::Testing::require(exec->join().has_value());
|
||||
// Both lanes drained; the completion lane (legacy post, then the explicit
|
||||
// completion) runs before the queued normal handle.
|
||||
Void::Testing::expect_eq(legacy_order.load(), 0);
|
||||
Void::Testing::expect_eq(completion_order.load(), 1);
|
||||
Void::Testing::expect_eq(queued_order.load(), 2);
|
||||
Void::Testing::expect(exec->idle());
|
||||
}
|
||||
|
||||
Void::Testing::Test thread_executor_join_self_join_on_worker()
|
||||
{
|
||||
std::atomic<int> code{-1};
|
||||
std::atomic<bool> observed_executor_thread{false};
|
||||
Fixture exec{1, 4};
|
||||
|
||||
auto job = make_job([&] {
|
||||
const auto joined = exec->join();
|
||||
code.store(joined.has_value() ? 0 : static_cast<int>(joined.error().code().value));
|
||||
observed_executor_thread.store(exec->is_executor_thread());
|
||||
});
|
||||
Void::Testing::require(exec->try_post(job.handle).has_value());
|
||||
Void::Testing::require(wait_until([&] { return code.load() != -1; }));
|
||||
Void::Testing::expect_eq(code.load(), static_cast<int>(AsyncErrorCode::self_join));
|
||||
Void::Testing::expect(observed_executor_thread.load());
|
||||
// A normal join from a non-executor thread still works afterwards.
|
||||
Void::Testing::expect(!exec->is_executor_thread());
|
||||
Void::Testing::require(exec->join().has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test thread_executor_partial_start_failure_joins_started()
|
||||
{
|
||||
std::atomic<int> hook_calls{0};
|
||||
std::atomic<bool> fail{true};
|
||||
std::atomic<int> ran{0};
|
||||
auto created = ThreadExecutor::create(ThreadExecutorOptions{
|
||||
.workers = 3,
|
||||
.max_admitted = 8,
|
||||
.before_worker_start = [&](std::size_t index) -> Void::Result::Result<void> {
|
||||
hook_calls.fetch_add(1);
|
||||
if (fail.load() && index == 2) {
|
||||
return std::unexpected{make_async_error(
|
||||
AsyncErrorCode::limit_exceeded, "injected thread start failure")};
|
||||
}
|
||||
return {};
|
||||
}});
|
||||
Void::Testing::require(created.has_value());
|
||||
auto& exec = **created;
|
||||
|
||||
// Work admitted before start() must not run on workers of a failed start.
|
||||
auto job = make_job([&ran] { ran.fetch_add(1); });
|
||||
Void::Testing::require(exec.try_post(job.handle).has_value());
|
||||
|
||||
const auto failed = exec.start();
|
||||
Void::Testing::require(!failed.has_value());
|
||||
Void::Testing::expect(async_code(failed.error()) == AsyncErrorCode::limit_exceeded);
|
||||
Void::Testing::expect_eq(hook_calls.load(), 3);
|
||||
std::this_thread::sleep_for(30ms);
|
||||
Void::Testing::expect_eq(ran.load(), 0);
|
||||
Void::Testing::expect_eq(exec.stats().queued, std::size_t{1});
|
||||
Void::Testing::expect_eq(exec.stats().running, std::size_t{0});
|
||||
|
||||
// The two workers that were already started were joined: a retry starts a
|
||||
// full set again.
|
||||
fail.store(false);
|
||||
Void::Testing::require(exec.start().has_value());
|
||||
Void::Testing::expect_eq(hook_calls.load(), 6);
|
||||
Void::Testing::expect(wait_until([&] { return ran.load() == 1; }));
|
||||
Void::Testing::require(exec.join().has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test thread_executor_system_error_path_shared_with_hook()
|
||||
{
|
||||
std::atomic<int> mode{0}; // 0 = ok, 1 = system_error, 2 = runtime_error
|
||||
std::atomic<int> hook_calls{0};
|
||||
std::atomic<int> ran{0};
|
||||
auto created = ThreadExecutor::create(ThreadExecutorOptions{
|
||||
.workers = 3,
|
||||
.max_admitted = 8,
|
||||
.before_worker_start = [&](std::size_t index) -> Void::Result::Result<void> {
|
||||
hook_calls.fetch_add(1);
|
||||
if (index == 1 && mode.load() == 1) {
|
||||
throw std::system_error{std::make_error_code(std::errc::resource_unavailable_try_again),
|
||||
"injected thread creation failure"};
|
||||
}
|
||||
if (index == 1 && mode.load() == 2) {
|
||||
throw std::runtime_error{"injected hook failure"};
|
||||
}
|
||||
return {};
|
||||
}});
|
||||
Void::Testing::require(created.has_value());
|
||||
auto& exec = **created;
|
||||
|
||||
auto job = make_job([&ran] { ran.fetch_add(1); });
|
||||
Void::Testing::require(exec.try_post(job.handle).has_value());
|
||||
|
||||
// std::system_error: same cleanup path as a hook error, system code kept.
|
||||
mode.store(1);
|
||||
const auto sys_failed = exec.start();
|
||||
Void::Testing::require(!sys_failed.has_value());
|
||||
Void::Testing::expect(async_code(sys_failed.error()) == AsyncErrorCode::backend_error);
|
||||
Void::Testing::expect(sys_failed.error().system_code() ==
|
||||
std::make_error_code(std::errc::resource_unavailable_try_again));
|
||||
Void::Testing::expect_eq(hook_calls.load(), 2);
|
||||
|
||||
// Any other exception takes the same path, without a system code.
|
||||
mode.store(2);
|
||||
const auto other_failed = exec.start();
|
||||
Void::Testing::require(!other_failed.has_value());
|
||||
Void::Testing::expect(async_code(other_failed.error()) == AsyncErrorCode::backend_error);
|
||||
Void::Testing::expect(!other_failed.error().system_code());
|
||||
Void::Testing::expect_eq(hook_calls.load(), 4);
|
||||
Void::Testing::expect_eq(ran.load(), 0);
|
||||
|
||||
mode.store(0);
|
||||
Void::Testing::require(exec.start().has_value());
|
||||
Void::Testing::expect(wait_until([&] { return ran.load() == 1; }));
|
||||
Void::Testing::require(exec.join().has_value());
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
Void::Coro::Task<void> hop_task(ThreadExecutor* exec,
|
||||
std::atomic<int>* stage,
|
||||
std::atomic<bool>* on_executor_before,
|
||||
std::atomic<bool>* on_executor_after,
|
||||
std::atomic<int>* status_code)
|
||||
{
|
||||
on_executor_before->store(exec->is_executor_thread());
|
||||
stage->store(1);
|
||||
co_await schedule_on(*exec);
|
||||
stage->store(2);
|
||||
const auto status = co_await schedule_on(*exec, OperationOptions{});
|
||||
status_code->store(status.has_value() ? 0 : static_cast<int>(status.error().code().value));
|
||||
on_executor_after->store(exec->is_executor_thread());
|
||||
stage->store(3);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test thread_executor_legacy_post_spawn_schedule_on_compat()
|
||||
{
|
||||
std::atomic<int> stage{0};
|
||||
std::atomic<bool> before{false};
|
||||
std::atomic<bool> after{false};
|
||||
std::atomic<int> status_code{-1};
|
||||
std::atomic<bool> blocker_running{false};
|
||||
std::atomic<int> ran{0};
|
||||
Fixture exec{1, 2};
|
||||
|
||||
// spawn() and schedule_on(executor) use the legacy post(): never rejected.
|
||||
// spawn() is called from the single worker itself, not from a foreign
|
||||
// thread: ThreadSanitizer reports a data race in Executor.hpp's spawn_impl
|
||||
// (lines 292/296) when spawn() is called from a thread other than the
|
||||
// executor's workers onto a multi-worker executor. That behaviour is
|
||||
// independent of ThreadExecutor and is escalated to the root; it is not
|
||||
// covered here.
|
||||
auto spawner = make_job([&] {
|
||||
spawn(*exec, hop_task(exec.exec.get(), &stage, &before, &after, &status_code));
|
||||
});
|
||||
Void::Testing::require(exec->try_post(spawner.handle).has_value());
|
||||
Void::Testing::require(wait_until([&] { return stage.load() == 3; }));
|
||||
Void::Testing::expect(before.load());
|
||||
Void::Testing::expect(after.load());
|
||||
Void::Testing::expect_eq(status_code.load(), 0);
|
||||
Void::Testing::expect(exec->stats().legacy_posts >= 2);
|
||||
|
||||
// A full bound (running + queued == 2) rejects try_post (and the status
|
||||
// schedule_on built on it) but never the legacy post.
|
||||
auto blocker = make_blocker(exec, blocker_running);
|
||||
Void::Testing::require(exec->try_post(blocker.handle).has_value());
|
||||
Void::Testing::require(wait_until([&] { return blocker_running.load(); }));
|
||||
auto filler = make_job([&ran] { ran.fetch_add(1); });
|
||||
Void::Testing::require(exec->try_post(filler.handle).has_value());
|
||||
auto rejected = make_job([] {});
|
||||
Void::Testing::expect(!exec->try_post(rejected.handle).has_value());
|
||||
rejected.handle.destroy();
|
||||
|
||||
const std::uint64_t legacy_before = exec->stats().legacy_posts;
|
||||
auto j1 = make_job([&ran] { ran.fetch_add(1); });
|
||||
auto j2 = make_job([&ran] { ran.fetch_add(1); });
|
||||
exec->post(j1.handle);
|
||||
exec->post(j2.handle);
|
||||
Void::Testing::expect_eq(exec->stats().legacy_posts, legacy_before + 2);
|
||||
Void::Testing::expect_eq(exec->admitted(), std::size_t{4});
|
||||
exec.gate.open();
|
||||
Void::Testing::expect(wait_until([&] { return ran.load() == 3; }));
|
||||
Void::Testing::require(exec->join().has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test thread_executor_inline_after_join_counted()
|
||||
{
|
||||
std::atomic<int> ran{0};
|
||||
std::mutex mu;
|
||||
std::vector<std::thread::id> threads;
|
||||
std::atomic<bool> guarded{false};
|
||||
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 4});
|
||||
Void::Testing::require(created.has_value());
|
||||
auto& exec = **created;
|
||||
Void::Testing::require(exec.start().has_value());
|
||||
|
||||
auto before_join = make_job([&] { ran.fetch_add(1); });
|
||||
Void::Testing::require(exec.try_post(before_join.handle).has_value());
|
||||
Void::Testing::require(exec.join().has_value());
|
||||
Void::Testing::expect_eq(ran.load(), 1);
|
||||
Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{0});
|
||||
|
||||
// After join, posts resume inline on the caller (counted), never dropped.
|
||||
const auto caller = std::this_thread::get_id();
|
||||
auto record = [&] {
|
||||
std::lock_guard lk{mu};
|
||||
threads.push_back(std::this_thread::get_id());
|
||||
guarded.store(exec.is_executor_thread());
|
||||
};
|
||||
auto j1 = make_job(record);
|
||||
exec.post(j1.handle);
|
||||
auto j2 = make_job(record);
|
||||
exec.post_completion(j2.handle);
|
||||
Void::Testing::expect_eq(threads.size(), std::size_t{2});
|
||||
Void::Testing::expect(threads[0] == caller);
|
||||
Void::Testing::expect(threads[1] == caller);
|
||||
// The inline resume runs under ExecutorThreadGuard.
|
||||
Void::Testing::expect(guarded.load());
|
||||
Void::Testing::expect(!exec.is_executor_thread());
|
||||
Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{2});
|
||||
Void::Testing::expect_eq(exec.stats().legacy_posts, std::uint64_t{1});
|
||||
|
||||
// Normal admission stays closed after join, and join/start are repeatable
|
||||
// or rejected.
|
||||
auto refused = make_job([] {});
|
||||
const auto stopped = exec.try_post(refused.handle);
|
||||
Void::Testing::expect(!stopped.has_value());
|
||||
Void::Testing::expect(stopped.error() == AdmissionError::stopped);
|
||||
refused.handle.destroy();
|
||||
const auto reserved = exec.try_reserve_slot();
|
||||
Void::Testing::expect(!reserved.has_value());
|
||||
Void::Testing::expect(reserved.error() == AdmissionError::stopped);
|
||||
Void::Testing::require(exec.join().has_value());
|
||||
const auto restarted = exec.start();
|
||||
Void::Testing::expect(!restarted.has_value());
|
||||
Void::Testing::expect(exec.idle());
|
||||
}
|
||||
|
||||
Void::Testing::Test thread_executor_join_without_start_drains_inline()
|
||||
{
|
||||
std::mutex mu;
|
||||
std::vector<int> order;
|
||||
std::atomic<bool> all_on_caller{true};
|
||||
const auto caller = std::this_thread::get_id();
|
||||
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 8});
|
||||
Void::Testing::require(created.has_value());
|
||||
auto& exec = **created;
|
||||
|
||||
auto make_marker = [&](int id) {
|
||||
return make_job([&, id] {
|
||||
std::lock_guard lk{mu};
|
||||
order.push_back(id);
|
||||
if (std::this_thread::get_id() != caller) {
|
||||
all_on_caller.store(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
auto n1 = make_marker(1);
|
||||
auto n2 = make_marker(2);
|
||||
auto c1 = make_marker(10);
|
||||
auto n3 = make_marker(3);
|
||||
Void::Testing::require(exec.try_post(n1.handle).has_value());
|
||||
Void::Testing::require(exec.try_post(n2.handle).has_value());
|
||||
exec.post_completion(c1.handle);
|
||||
exec.post(n3.handle);
|
||||
Void::Testing::expect_eq(exec.admitted(), std::size_t{3});
|
||||
|
||||
// No worker exists: join() drains both lanes inline, never waits.
|
||||
Void::Testing::require(exec.join().has_value());
|
||||
Void::Testing::expect(all_on_caller.load());
|
||||
// Completion lane first, then the normal lane in FIFO order.
|
||||
Void::Testing::expect_eq(order.size(), std::size_t{4});
|
||||
if (order.size() == 4) {
|
||||
Void::Testing::expect_eq(order[0], 10);
|
||||
Void::Testing::expect_eq(order[1], 1);
|
||||
Void::Testing::expect_eq(order[2], 2);
|
||||
Void::Testing::expect_eq(order[3], 3);
|
||||
}
|
||||
Void::Testing::expect_eq(exec.stats().inline_after_join, std::uint64_t{4});
|
||||
Void::Testing::expect(exec.idle());
|
||||
Void::Testing::expect(!exec.start().has_value());
|
||||
|
||||
// The destructor of a never-started executor also drains inline.
|
||||
std::atomic<int> ran{0};
|
||||
{
|
||||
auto second = ThreadExecutor::create();
|
||||
Void::Testing::require(second.has_value());
|
||||
auto pending = make_job([&ran] { ran.fetch_add(1); });
|
||||
Void::Testing::require((*second)->try_post(pending.handle).has_value());
|
||||
}
|
||||
Void::Testing::expect_eq(ran.load(), 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test thread_executor_start_twice_and_after_close_invalid()
|
||||
{
|
||||
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 2, .max_admitted = 4});
|
||||
Void::Testing::require(created.has_value());
|
||||
auto& exec = **created;
|
||||
Void::Testing::require(exec.start().has_value());
|
||||
const auto twice = exec.start();
|
||||
Void::Testing::require(!twice.has_value());
|
||||
Void::Testing::expect(async_code(twice.error()) == AsyncErrorCode::invalid_argument);
|
||||
|
||||
auto closed_created = ThreadExecutor::create();
|
||||
Void::Testing::require(closed_created.has_value());
|
||||
auto& closed = **closed_created;
|
||||
closed.close();
|
||||
const auto after_close = closed.start();
|
||||
Void::Testing::require(!after_close.has_value());
|
||||
Void::Testing::expect(async_code(after_close.error()) == AsyncErrorCode::invalid_argument);
|
||||
|
||||
Void::Testing::require(exec.join().has_value());
|
||||
const auto after_join = exec.start();
|
||||
Void::Testing::require(!after_join.has_value());
|
||||
Void::Testing::expect(async_code(after_join.error()) == AsyncErrorCode::invalid_argument);
|
||||
}
|
||||
|
||||
Void::Testing::Test thread_executor_reservation_across_close_binding()
|
||||
{
|
||||
std::atomic<int> ran{0};
|
||||
std::atomic<bool> joined{false};
|
||||
std::atomic<bool> join_ok{false};
|
||||
std::atomic<bool> job_on_joiner{false};
|
||||
|
||||
// (1) Workers running: a reservation taken before close() stays binding.
|
||||
{
|
||||
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2});
|
||||
Void::Testing::require(created.has_value());
|
||||
auto& exec = **created;
|
||||
Void::Testing::require(exec.start().has_value());
|
||||
Void::Testing::require(exec.try_reserve_slot().has_value());
|
||||
// A reserved slot counts in admitted() and in the bound.
|
||||
Void::Testing::expect_eq(exec.admitted(), std::size_t{1});
|
||||
Void::Testing::require(exec.try_reserve_slot().has_value());
|
||||
const auto full = exec.try_reserve_slot();
|
||||
Void::Testing::expect(!full.has_value());
|
||||
Void::Testing::expect(full.error() == AdmissionError::overloaded);
|
||||
exec.release_reserved();
|
||||
Void::Testing::expect_eq(exec.admitted(), std::size_t{1});
|
||||
|
||||
exec.close();
|
||||
const auto after_close = exec.try_reserve_slot();
|
||||
Void::Testing::expect(!after_close.has_value());
|
||||
Void::Testing::expect(after_close.error() == AdmissionError::stopped);
|
||||
Void::Testing::expect_eq(exec.admitted(), std::size_t{1});
|
||||
|
||||
std::thread joiner([&] {
|
||||
join_ok.store(exec.join().has_value());
|
||||
joined.store(true);
|
||||
});
|
||||
// join() also waits until no reservation is outstanding.
|
||||
std::this_thread::sleep_for(60ms);
|
||||
Void::Testing::expect(!joined.load());
|
||||
|
||||
auto job = make_job([&ran] { ran.fetch_add(1); });
|
||||
exec.commit_reserved(job.handle); // binding: enqueues normally after close()
|
||||
joiner.join();
|
||||
Void::Testing::expect(joined.load());
|
||||
Void::Testing::expect(join_ok.load());
|
||||
Void::Testing::expect_eq(ran.load(), 1);
|
||||
Void::Testing::expect_eq(exec.admitted(), std::size_t{0});
|
||||
}
|
||||
|
||||
// (2) A released reservation also lets join() finish (no workers: the
|
||||
// joiner drains inline, but still waits for the reservation).
|
||||
{
|
||||
joined.store(false);
|
||||
join_ok.store(false);
|
||||
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2});
|
||||
Void::Testing::require(created.has_value());
|
||||
auto& exec = **created;
|
||||
Void::Testing::require(exec.try_reserve_slot().has_value());
|
||||
std::thread joiner([&] {
|
||||
join_ok.store(exec.join().has_value());
|
||||
joined.store(true);
|
||||
});
|
||||
std::this_thread::sleep_for(60ms);
|
||||
Void::Testing::expect(!joined.load());
|
||||
exec.release_reserved();
|
||||
joiner.join();
|
||||
Void::Testing::expect(joined.load());
|
||||
Void::Testing::expect(join_ok.load());
|
||||
}
|
||||
|
||||
// (3) No workers + a commit after join() began: the committed handle is
|
||||
// drained by the joining thread.
|
||||
{
|
||||
joined.store(false);
|
||||
join_ok.store(false);
|
||||
const auto joiner_id = std::make_shared<std::atomic<std::thread::id>>();
|
||||
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 1, .max_admitted = 2});
|
||||
Void::Testing::require(created.has_value());
|
||||
auto& exec = **created;
|
||||
Void::Testing::require(exec.try_reserve_slot().has_value());
|
||||
std::thread joiner([&] {
|
||||
joiner_id->store(std::this_thread::get_id());
|
||||
join_ok.store(exec.join().has_value());
|
||||
joined.store(true);
|
||||
});
|
||||
std::this_thread::sleep_for(60ms);
|
||||
auto job = make_job([&] {
|
||||
job_on_joiner.store(std::this_thread::get_id() == joiner_id->load());
|
||||
ran.fetch_add(1);
|
||||
});
|
||||
exec.commit_reserved(job.handle);
|
||||
joiner.join();
|
||||
Void::Testing::expect(join_ok.load());
|
||||
Void::Testing::expect(job_on_joiner.load());
|
||||
Void::Testing::expect_eq(ran.load(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test thread_executor_stress_tsan()
|
||||
{
|
||||
constexpr int kPosters = 4;
|
||||
constexpr int kPerPoster = 1200;
|
||||
std::atomic<std::uint64_t> accepted{0};
|
||||
std::atomic<std::uint64_t> executed{0};
|
||||
std::atomic<std::uint64_t> posted_failed_unexpectedly{0};
|
||||
std::atomic<std::uint64_t> snapshot_inconsistent{0};
|
||||
std::vector<std::thread> posters;
|
||||
|
||||
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 3, .max_admitted = 32});
|
||||
Void::Testing::require(created.has_value());
|
||||
auto& exec = **created;
|
||||
Void::Testing::require(exec.start().has_value());
|
||||
|
||||
for (int p = 0; p < kPosters; ++p) {
|
||||
posters.emplace_back([&, p] {
|
||||
for (int k = 0; k < kPerPoster; ++k) {
|
||||
const int kind = (p + k) % 4;
|
||||
auto job = make_job([&executed] { executed.fetch_add(1, std::memory_order_relaxed); });
|
||||
if (post_one(exec, kind, job)) {
|
||||
accepted.fetch_add(1, std::memory_order_relaxed);
|
||||
} else {
|
||||
posted_failed_unexpectedly.fetch_add(1);
|
||||
}
|
||||
if ((k & 63) == 0) {
|
||||
const auto stats = exec.stats();
|
||||
if (stats.running > 3) {
|
||||
snapshot_inconsistent.fetch_add(1);
|
||||
}
|
||||
(void)exec.idle();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
for (auto& poster : posters) {
|
||||
poster.join();
|
||||
}
|
||||
// Repeated and concurrent join(): every caller returns success and the
|
||||
// worker threads are joined exactly once.
|
||||
std::atomic<int> concurrent_join_failures{0};
|
||||
std::vector<std::thread> joiners;
|
||||
for (int j = 0; j < 3; ++j) {
|
||||
joiners.emplace_back([&] {
|
||||
if (!exec.join().has_value()) {
|
||||
concurrent_join_failures.fetch_add(1);
|
||||
}
|
||||
});
|
||||
}
|
||||
const bool main_join_ok = exec.join().has_value();
|
||||
for (auto& joiner : joiners) {
|
||||
joiner.join();
|
||||
}
|
||||
Void::Testing::require(main_join_ok);
|
||||
Void::Testing::expect_eq(concurrent_join_failures.load(), 0);
|
||||
|
||||
Void::Testing::expect_eq(posted_failed_unexpectedly.load(), std::uint64_t{0});
|
||||
Void::Testing::expect_eq(snapshot_inconsistent.load(), std::uint64_t{0});
|
||||
Void::Testing::expect_eq(accepted.load(), static_cast<std::uint64_t>(kPosters) * kPerPoster);
|
||||
Void::Testing::expect_eq(executed.load(), accepted.load());
|
||||
Void::Testing::expect(exec.idle());
|
||||
Void::Testing::expect_eq(exec.admitted(), std::size_t{0});
|
||||
}
|
||||
|
||||
// Regression (W11): spawn() from a foreign thread onto a multi-worker executor
|
||||
// must not race with the worker that resumes and destroys the detached frame.
|
||||
namespace
|
||||
{
|
||||
Void::Coro::Task<void> spawn_bump(std::atomic<int>* counter)
|
||||
{
|
||||
counter->fetch_add(1, std::memory_order_relaxed);
|
||||
co_return;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test thread_executor_spawn_from_foreign_thread_multi_worker_tsan()
|
||||
{
|
||||
auto created = ThreadExecutor::create(ThreadExecutorOptions{.workers = 4, .max_admitted = 64});
|
||||
Void::Testing::require(created.has_value());
|
||||
auto& exec = **created;
|
||||
Void::Testing::require(exec.start().has_value());
|
||||
|
||||
constexpr int kSpawns = 2000;
|
||||
std::atomic<int> counter{0};
|
||||
for (int i = 0; i < kSpawns; ++i) {
|
||||
spawn(exec, spawn_bump(&counter));
|
||||
}
|
||||
Void::Testing::require(exec.join().has_value());
|
||||
Void::Testing::expect_eq(counter.load(std::memory_order_relaxed), kSpawns);
|
||||
}
|
||||
Reference in new issue
Block a user