CoriEngine
Loading...
Searching...
No Matches
ThreadPool.hpp
Go to the documentation of this file.
1#pragma once
2
3#if 1
4namespace Cori {
5 namespace Core {
6 namespace Threading {
7 class ThreadPool {
8 public:
9 explicit ThreadPool(const uint16_t numThreads) : m_WorkerCount(numThreads) {
10 for (uint16_t i = 0; i < numThreads; ++i) {
11 m_Workers.emplace_back([this] {
12 while (true) {
13 std::function<void()> task;
14 {
15 std::unique_lock lock(this->m_QueueMutex);
16 this->m_Condition.wait(lock, [this] {
17 return this->m_Stop || !this->m_Tasks.empty();
18 });
19
20 if (this->m_Stop && this->m_Tasks.empty()) {
21 return;
22 }
23
24 task = std::move(this->m_Tasks.front());
25 this->m_Tasks.pop();
26 }
27 task();
28 }
29 });
30 }
31 }
32
34 {
35 std::unique_lock lock(m_QueueMutex);
36 m_Stop = true;
37 }
38 m_Condition.notify_all();
39 for (std::thread& worker : m_Workers) {
40 worker.join();
41 }
42 }
43
48 uint16_t GetWorkerCount() const {
49 return m_WorkerCount;
50 }
51
61 template <class F, class... Args>
62 std::future<std::invoke_result_t<F, Args...>> Submit(F&& f, Args&&... args) {
63 using ReturnType = std::invoke_result_t<F, Args...>;
64
65 auto task = std::make_shared<std::packaged_task<ReturnType()>>(
66 std::bind(std::forward<F>(f), std::forward<Args>(args)...)
67 );
68
69 std::future<ReturnType> res = task->get_future();
70
71 {
72 std::unique_lock lock(m_QueueMutex);
73
74 if (m_Stop) {
75 throw std::runtime_error("Submit on stopped ThreadPool");
76 }
77
78 m_Tasks.emplace([task]() { (*task)(); });
79 }
80 m_Condition.notify_one();
81
82 return res;
83 }
84
85 private:
86 std::vector<std::thread> m_Workers;
87 std::queue<std::function<void()>> m_Tasks;
88 std::mutex m_QueueMutex;
89 std::condition_variable m_Condition;
90 uint16_t m_WorkerCount{ 0 };
91 bool m_Stop{ false };
92 };
93 }
94 }
95}
96#endif
uint16_t GetWorkerCount() const
Returns a number of threads allocated for this thread pool.
std::future< std::invoke_result_t< F, Args... > > Submit(F &&f, Args &&... args)
Submits a task to be executed on the thread of this thread pool.
ThreadPool(const uint16_t numThreads)
Definition ThreadPool.hpp:9
Core systems of the engine are here.
Global engine namespace.