10#include <condition_variable>
48class TOAST_API ThreadPool {
59 static auto create()
noexcept -> std::unique_ptr<ThreadPool>;
77 static auto push(T&& job) -> std::future<std::invoke_result_t<T>>;
80 static void pushRaw(std::move_only_function<
void()>&& job);
100 [[nodiscard]] [[deprecated(
"Use waitIdle() instead")]]
111 static auto workerCount() -> size_t;
122 ThreadPool(ThreadPool&) =
delete;
123 ThreadPool(ThreadPool&&) =
delete;
124 auto operator=(
const ThreadPool&) -> ThreadPool& =
delete;
125 auto operator=(ThreadPool&&) -> ThreadPool& =
delete;
134 inline static ThreadPool* instance =
nullptr;
135 static auto get()
noexcept -> ThreadPool&;
138 static void enqueue(std::move_only_function<
void()>&& job);
148 std::queue<std::move_only_function<void()>>
jobs;
154 using result_t = std::invoke_result_t<T>;
156 std::packaged_task<result_t()> task(std::forward<T>(job));
157 auto future = task.get_future();
158 enqueue([task = std::move(task)]()
mutable { task(); });
static void pushRaw(std::move_only_function< void()> &&job)
Queues a job with no std::future the caller synchronizes completion itself same queue and workers as ...
Definition thread_pool.cpp:17
std::condition_variable all_done
Notified when activeJobs hits 0 and queue is empty.
Definition thread_pool.hpp:146
auto busy() -> bool
Checks if the pool has pending or in-flight jobs.
Definition thread_pool.cpp:49
static auto push(T &&job) -> std::future< std::invoke_result_t< T > >
Queues a job for execution by a worker thread.
Definition thread_pool.hpp:153
void waitIdle()
Blocks the calling thread until all queued and active jobs complete.
Definition thread_pool.cpp:54
std::atomic< int > idle_workers
Number of workers waiting for a job.
Definition thread_pool.hpp:143
std::queue< std::move_only_function< void()> > jobs
Pending job queue.
Definition thread_pool.hpp:148
bool should_stop
Flag to signal workers to stop.
Definition thread_pool.hpp:141
std::mutex queue_mutex
Mutex protecting the job queue.
Definition thread_pool.hpp:144
static auto create() noexcept -> std::unique_ptr< ThreadPool >
Initializes the pool and returns a pointer with ownership.
Definition thread_pool.cpp:116
static auto onWorkerThread() noexcept -> bool
Definition thread_pool.cpp:63
std::atomic< int > active_jobs
Number of jobs currently executing.
Definition thread_pool.hpp:142
std::condition_variable job_available
Notified when a job is enqueued or stop is requested.
Definition thread_pool.hpp:145
static auto idleWorkers() noexcept -> size_t
Definition thread_pool.cpp:71
void destroy()
Destroys the thread pool and waits for all workers to finish.
Definition thread_pool.cpp:32
std::vector< std::jthread > workers
Worker threads (auto-join on destruction).
Definition thread_pool.hpp:147