Files
Library/include/Void/Async/ThreadPool.hpp
T
faumarayandClaude Opus 4.8 80293ee56f Add async/resilience/reflection primitives + FSM v2 rewrite
A round of new universal capabilities (all generic — templated/reflection
based, no app coupling), verified by the test suite (1103 passing):

Data reflection:
- Reflect.hpp now (de)serializes chrono::duration, chrono::time_point,
  std::variant (tagged), std::array, and non-string-keyed std::map;
  Meta.hpp gains is_time_point_v et al.

Async:
- EventBus gains Mode::Async (worker-thread dispatch + flush()).
- ThreadPool gains a bounded queue, try_submit(), and rejection stats.

New modules / containers:
- Resilience: TokenBucket, KeyedRateLimiter<Key>, CircuitBreaker,
  ResourceMonitor.
- Containers: BufferPool<T> (size-class buffer reuse) and Cache<K,V>
  (per-entry TTL, LRU/LFU/FIFO eviction, hit/miss stats).
- System: process/CPU/memory metrics (Metrics.hpp) and a streaming
  Process API.

Plus FSM v2 (typed Success/Failure, sub-machines, parallel regions,
history states, deferred events), Configuration/Logging reflection
helpers, and the accompanying test suites.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 15:45:16 +03:00

190 lines
4.7 KiB
C++

#pragma once
#include <Void/Log/Log.hpp>
#include <atomic>
#include <condition_variable>
#include <cstdint>
#include <format>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <queue>
#include <stdexcept>
#include <thread>
#include <vector>
namespace Void::Concurrency
{
class ThreadPool
{
public:
// A snapshot of throughput / backpressure counters.
struct Stats {
std::uint64_t submitted =
0; // tasks accepted onto the queue
std::uint64_t completed = 0; // tasks finished running
std::uint64_t rejected = 0; // try_submit refusals (full)
std::size_t pending = 0; // tasks currently queued
};
// `max_queue == 0` keeps the queue unbounded (the historical
// behavior). A non-zero bound makes submit() block for space and
// try_submit() reject when the queue is full.
explicit ThreadPool(
std::size_t n = std::thread::hardware_concurrency(),
std::size_t max_queue = 0)
: max_queue_{max_queue}
{
const std::size_t count = (n > 0) ? n : 1;
workers_.reserve(count);
for (std::size_t i = 0; i < count; ++i) {
workers_.emplace_back([this] { worker_loop(); });
}
Void::Log::debug("Concurrency",
"ThreadPool: started with {} threads", count);
}
~ThreadPool()
{
Void::Log::debug("Concurrency", "ThreadPool: stopping");
{
std::unique_lock lock{mu_};
stop_ = true;
}
cv_.notify_all();
not_full_.notify_all();
for (auto& w : workers_) {
w.join();
}
}
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
ThreadPool(ThreadPool&&) = delete;
ThreadPool& operator=(ThreadPool&&) = delete;
// Enqueue a task. On a bounded pool this blocks until the queue has
// space (backpressure); on an unbounded pool it never blocks.
template <std::invocable F>
auto submit(F&& f) -> std::future<std::invoke_result_t<F>>
{
using R = std::invoke_result_t<F>;
auto task = std::make_shared<std::packaged_task<R()>>(
std::forward<F>(f));
auto fut = task->get_future();
{
std::unique_lock lock{mu_};
if (max_queue_ > 0) {
not_full_.wait(lock, [this] {
return stop_ || queue_.size() < max_queue_;
});
}
if (stop_) {
throw std::runtime_error(
"Void::Concurrency::ThreadPool: submit after "
"shutdown");
}
push_locked(task);
}
cv_.notify_one();
return fut;
}
// Non-blocking enqueue. Returns nullopt when a bounded queue is
// full (recording a rejection) or after shutdown; otherwise the
// future.
template <std::invocable F>
auto try_submit(F&& f)
-> std::optional<std::future<std::invoke_result_t<F>>>
{
using R = std::invoke_result_t<F>;
auto task = std::make_shared<std::packaged_task<R()>>(
std::forward<F>(f));
auto fut = task->get_future();
{
std::unique_lock lock{mu_};
if (stop_) {
return std::nullopt;
}
if (max_queue_ > 0 && queue_.size() >= max_queue_) {
rejected_.fetch_add(1, std::memory_order_relaxed);
return std::nullopt;
}
push_locked(task);
}
cv_.notify_one();
return fut;
}
std::size_t thread_count() const noexcept
{
return workers_.size();
}
std::size_t pending_count() const
{
std::unique_lock lock{mu_};
return queue_.size();
}
[[nodiscard]] Stats stats() const
{
std::unique_lock lock{mu_};
return Stats{
submitted_.load(std::memory_order_relaxed),
completed_.load(std::memory_order_relaxed),
rejected_.load(std::memory_order_relaxed),
queue_.size(),
};
}
private:
template <typename R>
void push_locked(std::shared_ptr<std::packaged_task<R()>> task)
{
queue_.push([this, task] {
(*task)();
completed_.fetch_add(1, std::memory_order_relaxed);
});
submitted_.fetch_add(1, std::memory_order_relaxed);
}
void worker_loop()
{
for (;;) {
std::function<void()> task;
{
std::unique_lock lock{mu_};
cv_.wait(lock,
[this] { return stop_ || !queue_.empty(); });
if (stop_ && queue_.empty()) {
return;
}
task = std::move(queue_.front());
queue_.pop();
}
if (max_queue_ > 0) {
not_full_.notify_one();
}
task();
}
}
std::size_t max_queue_;
std::vector<std::thread> workers_;
std::queue<std::function<void()>> queue_;
mutable std::mutex mu_;
std::condition_variable cv_;
std::condition_variable not_full_;
std::atomic<std::uint64_t> submitted_{0};
std::atomic<std::uint64_t> completed_{0};
std::atomic<std::uint64_t> rejected_{0};
bool stop_{false};
};
} // namespace Void::Concurrency