3#include <condition_variable>
24 explicit ThreadPool(uint32_t threadCount = std::thread::hardware_concurrency());
34 template <
typename F,
typename... Args>
35 auto Enqueue(F&& f, Args&&... args);
51 std::vector<std::thread> workers_;
52 std::queue<std::function<void()>> tasks_;
54 std::mutex queue_mutex_;
55 std::condition_variable condition_;
56 std::condition_variable drained_;
57 uint32_t active_tasks_ = 0;
61template <
typename F,
typename... Args>
64 using ReturnType = std::invoke_result_t<F, Args...>;
66 auto task = std::make_shared<std::packaged_task<ReturnType()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
67 auto result = task->get_future();
69 std::unique_lock lock(queue_mutex_);
72 throw std::runtime_error(
"Enqueue called on a stopped ThreadPool");
75 tasks_.emplace([task]() { (*task)(); });
77 condition_.notify_one();
A fixed-size pool of threads.
Definition thread_pool.h:18
ThreadPool(uint32_t threadCount=std::thread::hardware_concurrency())
Constructs the pool with the given number of threads. Defaults to the hardware concurrency.
Definition thread_pool.cc:5
auto Enqueue(F &&f, Args &&... args)
Enqueues a task to be executed by the thread pool.
Definition thread_pool.h:62
void Wait()
Waits until the task queue is empty.
Definition thread_pool.cc:65
~ThreadPool()
Waits for all tasks to complete and then stops the pool.
Definition thread_pool.cc:51
const std::vector< std::thread > & GetWorkers() const
Returns the worker threads.
Definition thread_pool.h:45