PixelBullet  0.0.1
A C++ game engine
Loading...
Searching...
No Matches
thread_pool.h
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{
19public:
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 workers_;
48 }
49
50private:
51 std::vector<std::thread> workers_;
52 std::queue<std::function<void()>> tasks_;
53
54 std::mutex queue_mutex_;
55 std::condition_variable condition_;
56 std::condition_variable drained_;
57 uint32_t active_tasks_ = 0;
58 bool stop_ = false;
59};
60
61template <typename F, typename... Args>
62auto ThreadPool::Enqueue(F&& f, Args&&... args)
63{
64 using ReturnType = std::invoke_result_t<F, Args...>;
65
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();
68 {
69 std::unique_lock lock(queue_mutex_);
70 if (stop_)
71 {
72 throw std::runtime_error("Enqueue called on a stopped ThreadPool");
73 }
74
75 tasks_.emplace([task]() { (*task)(); });
76 }
77 condition_.notify_one();
78 return result;
79}
80} // namespace pixelbullet
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