Sane C++ Libraries
C++ Platform Abstraction Libraries
ThreadPool.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "Threading.h"
5
6namespace SC
7{
8struct ThreadPool;
9struct ThreadPoolTask;
10} // namespace SC
11
14
19{
20
21 Function<void()> function;
22 private:
23 friend struct ThreadPool;
24 ThreadPool* threadPool = nullptr;
25 ThreadPoolTask* next = nullptr;
26};
27
41{
42 using Task = ThreadPoolTask;
43
44 ThreadPool() = default;
45 ~ThreadPool() { (void)destroy(); }
46
48 [[nodiscard]] Result create(size_t workerThreads);
49
52 [[nodiscard]] Result destroy();
53
55 [[nodiscard]] Result queueTask(Task& task);
56
58 [[nodiscard]] Result waitForAllTasks();
59
61 [[nodiscard]] Result waitForTask(Task& task);
62
63 private:
64 Task* taskHead = nullptr; // Head of the FIFO linked list containing all threads
65 Task* taskTail = nullptr; // Tail of the FIFO linked list containing all threads
66
67 size_t numRunningTasks = 0; // How many tasks are running in this moment
68 size_t numWorkerThreads = 0; // How many worker threads exist in this pool (== 0 means uninitialized threadpool)
69
70 Mutex poolMutex; // Protects all ThreadPool members access from worker threads
71 ConditionVariable taskAvailable; // Signals to worker threads that there is a new queued task available
72 ConditionVariable taskCompleted; // Signals to threadpool that there is a new task that was completed
73
74 bool stopRequested = false; // Signals background threads to end their infinite task processing loop
75
76 struct WorkerThread;
77};
78
A native OS condition variable.
Definition: Threading.h:63
Wraps function pointers, member functions and lambdas without ever allocating.
Definition: Function.h:50
A native OS mutex to synchronize access to shared resources.
Definition: Threading.h:28
An ascii string used as boolean result. SC_TRY macro forwards errors to caller.
Definition: Result.h:12
Simple thread pool that executes tasks in a fixed number of worker threads.
Definition: ThreadPool.h:41
Result destroy()
Destroy the thread pool created previously with ThreadPool::create.
Result queueTask(Task &task)
Queue a task (that should not be already in use)
Result waitForTask(Task &task)
Blocks execution until all queued and pending tasks will be fully completed.
Result create(size_t workerThreads)
Create a thread pool with the requested number of worker threads.
Result waitForAllTasks()
Blocks execution until all queued and pending tasks will be fully completed.
A small task containing a function to execute that can be queued in the thread pool.
Definition: ThreadPool.h:19