vkmEngine 1.0.15
A C++ game engine · vkmengine.com
Loading...
Searching...
No Matches
thread_pool.h
1#pragma once
2
3#include <algorithm>
4#include <atomic>
5#include <condition_variable>
6#include <deque>
7#include <exception>
8#include <functional>
9#include <mutex>
10#include <thread>
11#include <vector>
12
13namespace Vkm::Engine {
14
23class ThreadPool {
24 public:
32 class Batch {
33 public:
40 template<typename Fn>
41 explicit Batch(const Fn& task)
42 : m_run([](const void* body, size_t index) { (*static_cast<const Fn*>(body))(index); })
43 , m_task(&task)
44 {}
45
47 template<typename Fn>
48 explicit Batch(const Fn && task) = delete;
49
50 ~Batch() = default;
51
52 Batch(const Batch& other) = delete;
53 Batch& operator=(const Batch& other) = delete;
54
55 Batch(Batch && other) = delete;
56 Batch& operator=(Batch && other) = delete;
57
58 private:
59 friend class ThreadPool;
60
61 private:
62 void (*m_run)(const void* task, size_t index);
63 const void* m_task;
64 size_t m_count = 0;
65 size_t m_claimed = 0;
66 std::exception_ptr m_error;
67
68 std::atomic<size_t> m_pending{0};
69 };
70
71 public:
72 ThreadPool(const ThreadPool& other) = delete;
73 ThreadPool& operator=(const ThreadPool& other) = delete;
74
75 ThreadPool(ThreadPool && other) = delete;
76 ThreadPool& operator=(ThreadPool && other) = delete;
77
78 public:
84 static ThreadPool& get();
85
93 void addTask(std::function<void()> && task);
94
104 void addBatch(Batch& batch, size_t count);
105
114 void waitForBatch(Batch& batch);
115
123 void shutdown();
124
133 static bool isWorkerThread();
134
135 size_t threadCount() const { return m_threads.size(); }
136
137 private:
143 struct QueuedTask {
144 std::function<void()> function;
145 Batch* batch = nullptr;
146 size_t index = 0;
147 };
148
149 private:
150 ThreadPool(size_t threadCount);
151 ~ThreadPool();
152
156 void process();
157
166 void runIndex(Batch& batch, size_t index);
167
176 void retire(std::atomic<size_t>& pending);
177
178 private:
179 std::atomic<bool> m_running;
180
181 std::vector<std::thread> m_threads;
182
183 std::deque<QueuedTask> m_frameTasks;
184 std::deque<QueuedTask> m_backgroundTasks;
185
186 std::mutex m_tasksMutex;
187 std::condition_variable m_tasksCV;
188 std::condition_variable m_doneCV;
189};
190
203template<class Function>
204void parallelFor(size_t count, size_t grain, Function&& function) {
205 if (count == 0) {
206 return;
207 }
208
209 grain = std::max(grain, size_t(1));
210
212 for (size_t i = 0; i < count; ++i) function(i);
213 return;
214 }
215
216 auto& pool = ThreadPool::get();
217
218 // No workers after shutdown (or with no cores reported): a submission would never retire.
219 if (pool.threadCount() == 0) {
220 for (size_t i = 0; i < count; ++i) function(i);
221 return;
222 }
223
224 // Chunk 0 is the caller's; batch index i is chunk i + 1.
225 const size_t chunks = (count - 1) / grain + 1;
226 const auto runChunk = [&](size_t chunk) {
227 const size_t end = std::min(count, (chunk + 1) * grain);
228 for (size_t index = chunk * grain; index < end; ++index) function(index);
229 };
230 const auto runQueued = [&](size_t task) { runChunk(task + 1); };
231 ThreadPool::Batch batch(runQueued);
232
233 pool.addBatch(batch, chunks - 1);
234
235 // Queued indices reach into this frame, so join before the caller's exception leaves it;
236 // that exception, not a queued chunk's, propagates.
237 try {
238 runChunk(0);
239 } catch (...) {
240 try {
241 pool.waitForBatch(batch);
242 } catch (...) {
243 }
244 throw;
245 }
246 pool.waitForBatch(batch);
247}
248
260template<class Function>
261void parallelFor(size_t count, Function&& function) {
262 auto& pool = ThreadPool::get();
263
264 // Below this the dispatch cost (mutex, notify_all, done-CV round trip) dwarfs the work;
265 // grain == count sweeps serially.
266 constexpr size_t MIN_PARALLEL = 2048;
267
268 // Each chunk is one claim on the pool's lock.
269 constexpr size_t CHUNKS_PER_THREAD = 8;
270
271 // The +1 is the calling thread, which runs chunks too.
272 const size_t grain = (count < MIN_PARALLEL)
273 ? count
274 : std::max<size_t>(count / ((pool.threadCount() + 1) * CHUNKS_PER_THREAD), 1);
275
276 parallelFor(count, grain, function);
277}
278
279} // namespace Vkm::Engine
A run of tasks addressed by index, queued as one entry.
Definition thread_pool.h:32
Batch(const Fn &task)
A batch whose every index is a call of task; addBatch says how many.
Definition thread_pool.h:41
Batch(const Fn &&task)=delete
Refused: a temporary task is gone before a worker reaches it.
Fixed-size pool of worker threads draining two task queues.
Definition thread_pool.h:23
void addBatch(Batch &batch, size_t count)
Queue indices 0 to count of batch as one entry and wake all workers.
static bool isWorkerThread()
True when called from a thread owned by the pool.
void shutdown()
Join the workers now, ahead of the pool's own destruction.
void addTask(std::function< void()> &&task)
Enqueue a single task and wake one worker.
void waitForBatch(Batch &batch)
Block the caller until every index of batch has retired.
static ThreadPool & get()
Access the process-wide thread pool, constructed on first use.