Run deterministic world stages on the bounded Void executor

This commit is contained in:
faumaray committed 2026-12-02 21:27:32 +03:00
1 parent 8d2870a6f8
commit 68f91a236a
10 files changed
+400 -81

No files matched your search

+29 -40
View File
@@ -3,54 +3,43 @@
#include <stdexcept>
namespace settlement {
namespace {
WorkerPool::WorkerPool(std::size_t thread_count) {
std::unique_ptr<Void::Async::ThreadExecutor> start_executor(
std::size_t thread_count, const WorkerPoolOptions& options) {
if (thread_count < 2) {
throw std::invalid_argument("worker pool needs at least two threads");
}
workers_.reserve(thread_count);
try {
for (std::size_t index = 0; index < thread_count; ++index) {
workers_.emplace_back([this] { worker_loop(); });
}
} catch (...) {
{
std::lock_guard<std::mutex> lock(mutex_);
stopping_ = true;
}
work_available_.notify_all();
for (std::thread& worker : workers_) {
if (worker.joinable()) worker.join();
}
throw;
if (options.max_admitted == 0) {
throw std::invalid_argument("worker pool capacity must be positive");
}
Void::Async::ThreadExecutorOptions settings;
settings.workers = thread_count;
settings.max_admitted = options.max_admitted;
if (options.before_worker_start) {
settings.before_worker_start = [hook = options.before_worker_start](std::size_t index)
-> Void::Result::Result<void> {
hook(index);
return {};
};
}
auto executor = Void::Async::ThreadExecutor::create(std::move(settings));
if (!executor) throw std::runtime_error(executor.error().message());
const auto started = (*executor)->start();
if (!started) throw std::runtime_error(started.error().message());
return std::move(*executor);
}
WorkerPool::~WorkerPool() {
{
std::lock_guard<std::mutex> lock(mutex_);
stopping_ = true;
}
work_available_.notify_all();
for (std::thread& worker : workers_) {
if (worker.joinable()) worker.join();
}
}
} // namespace
std::size_t WorkerPool::thread_count() const noexcept { return workers_.size(); }
WorkerPool::WorkerPool(std::size_t thread_count, WorkerPoolOptions options)
: thread_count_(thread_count), options_(std::move(options)),
executor_(start_executor(thread_count, options_)), futures_(*executor_) {}
void WorkerPool::worker_loop() {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mutex_);
work_available_.wait(lock, [this] { return stopping_ || !tasks_.empty(); });
if (stopping_ && tasks_.empty()) return;
task = std::move(tasks_.front());
tasks_.pop();
}
task();
}
}
// ThreadExecutor's destructor closes admission and joins every accepted task.
// options_ outlives that join so fault-hook captures remain valid through shutdown.
WorkerPool::~WorkerPool() = default;
std::size_t WorkerPool::thread_count() const noexcept { return thread_count_; }
} // namespace settlement