PixelBullet  0.0.1
A C++ game engine
Loading...
Searching...
No Matches
ThreadPool.hpp
1#pragma once
2
3#include <condition_variable>
4#include <functional>
5#include <future>
6#include <mutex>
7#include <queue>
8#include <stdexcept>
9#include <thread>
10#include <vector>
11
12namespace PixelBullet
13{
18 {
19 public:
24 explicit ThreadPool(uint32_t threadCount = std::thread::hardware_concurrency());
25
30
34 template <typename F, typename... Args>
35 auto Enqueue(F&& f, Args&&... args);
36
40 void Wait();
41
45 const std::vector<std::thread>& GetWorkers() const
46 {
47 return m_Workers;
48 }
49
50 private:
51 std::vector<std::thread> m_Workers;
52 std::queue<std::function<void()>> m_Tasks;
53
54 std::mutex m_QueueMutex;
55 std::condition_variable m_Condition;
56 bool m_Stop = false;
57 };
58
59 template <typename F, typename... Args>
60 auto ThreadPool::Enqueue(F&& f, Args&&... args)
61 {
62 using ReturnType = std::invoke_result_t<F, Args...>;
63
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();
67 {
68 std::unique_lock lock(m_QueueMutex);
69 if (m_Stop)
70 {
71 throw std::runtime_error("Enqueue called on a stopped ThreadPool");
72 }
73
74 m_Tasks.emplace([task]() { (*task)(); });
75 }
76 m_Condition.notify_one();
77 return result;
78 }
79} // namespace PixelBullet
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