5#include <condition_variable>
13namespace Vkm::Engine {
42 : m_run([](const void* body, size_t index) { (*
static_cast<const Fn*
>(body))(index); })
48 explicit Batch(
const Fn && task) =
delete;
59 friend class ThreadPool;
62 void (*m_run)(
const void* task,
size_t index);
66 std::exception_ptr m_error;
68 std::atomic<size_t> m_pending{0};
84 static ThreadPool&
get();
93 void addTask(std::function<
void()> && task);
135 size_t threadCount()
const {
return m_threads.size(); }
144 std::function<void()> function;
145 Batch* batch =
nullptr;
150 ThreadPool(
size_t threadCount);
166 void runIndex(Batch& batch,
size_t index);
176 void retire(std::atomic<size_t>& pending);
179 std::atomic<bool> m_running;
181 std::vector<std::thread> m_threads;
183 std::deque<QueuedTask> m_frameTasks;
184 std::deque<QueuedTask> m_backgroundTasks;
186 std::mutex m_tasksMutex;
187 std::condition_variable m_tasksCV;
188 std::condition_variable m_doneCV;
203template<
class Function>
204void parallelFor(
size_t count,
size_t grain, Function&& function) {
209 grain = std::max(grain,
size_t(1));
212 for (
size_t i = 0; i < count; ++i) function(i);
219 if (pool.threadCount() == 0) {
220 for (
size_t i = 0; i < count; ++i) function(i);
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);
230 const auto runQueued = [&](
size_t task) { runChunk(task + 1); };
233 pool.addBatch(batch, chunks - 1);
241 pool.waitForBatch(batch);
246 pool.waitForBatch(batch);
260template<
class Function>
261void parallelFor(
size_t count, Function&& function) {
266 constexpr size_t MIN_PARALLEL = 2048;
269 constexpr size_t CHUNKS_PER_THREAD = 8;
272 const size_t grain = (count < MIN_PARALLEL)
274 : std::max<size_t>(count / ((pool.threadCount() + 1) * CHUNKS_PER_THREAD), 1);
276 parallelFor(count, grain, function);
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.