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> m_Workers;
52 std::queue<std::function<void()>> m_Tasks;
54 std::mutex m_QueueMutex;
55 std::condition_variable m_Condition;
59 template <
typename F,
typename... Args>
62 using ReturnType = std::invoke_result_t<F, Args...>;
64 auto task = std::make_shared<std::packaged_task<ReturnType()>>(
65 std::bind(std::forward<F>(f), std::forward<Args>(args)...));
66 auto result = task->get_future();
68 std::unique_lock lock(m_QueueMutex);
71 throw std::runtime_error(
"Enqueue called on a stopped ThreadPool");
74 m_Tasks.emplace([task]() { (*task)(); });
76 m_Condition.notify_one();
A fixed-size pool of threads.
Definition ThreadPool.hpp:18
const std::vector< std::thread > & GetWorkers() const
Returns the worker threads.
Definition ThreadPool.hpp:45
ThreadPool(uint32_t threadCount=std::thread::hardware_concurrency())
Constructs the pool with the given number of threads. Defaults to the hardware concurrency.
Definition ThreadPool.cpp:5
auto Enqueue(F &&f, Args &&... args)
Enqueues a task to be executed by the thread pool.
Definition ThreadPool.hpp:60
void Wait()
Waits until the task queue is empty.
Definition ThreadPool.cpp:49
~ThreadPool()
Waits for all tasks to complete and then stops the pool.
Definition ThreadPool.cpp:35