Sane C++ Libraries
C++ Platform Abstraction Libraries
Loading...
Searching...
No Matches
ThreadPool.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "../Threading/Threading.h"
5
6namespace SC
7{
8struct SC_THREADING_EXPORT ThreadPool;
11
15struct SC_THREADING_EXPORT ThreadPoolTask
16{
17
18 Function<void()> function;
19
24 Function<void()> afterRelease;
25
26 private:
27 friend struct ThreadPool;
28 ThreadPool* threadPool = nullptr;
29 ThreadPoolTask* next = nullptr;
30};
31
44struct SC_THREADING_EXPORT ThreadPool
45{
46 using Task = ThreadPoolTask;
47
48 ThreadPool() = default;
49 ~ThreadPool() { (void)destroy(); }
50
52 ResultThreading create(size_t workerThreads);
53
57
60
63
66
67 private:
68 Task* taskHead = nullptr; // Head of the FIFO linked list containing all threads
69 Task* taskTail = nullptr; // Tail of the FIFO linked list containing all threads
70
71 size_t numRunningTasks = 0; // How many tasks are running in this moment
72 size_t numWorkerThreads = 0; // How many worker threads exist in this pool (== 0 means uninitialized threadpool)
73
74 Mutex poolMutex; // Protects all ThreadPool members access from worker threads
75 ConditionVariable taskAvailable; // Signals to worker threads that there is a new queued task available
76 ConditionVariable taskCompleted; // Signals to threadpool that there is a new task that was completed
77
78 bool stopRequested = false; // Signals background threads to end their infinite task processing loop
79
80 struct WorkerThread;
81};
82
84} // namespace SC
A native OS condition variable.
Definition Threading.h:72
A native OS mutex to synchronize access to shared resources.
Definition Threading.h:37
Threading result retaining optional native and backend-stage details.
Definition ThreadingError.h:49
A small task containing a function to execute that can be queued in the thread pool.
Definition ThreadPool.h:16
Function< void()> function
Function that will be executed during the task.
Definition ThreadPool.h:18
Function< void()> afterRelease
Optional worker notification after an executed task node is released.
Definition ThreadPool.h:24
Simple thread pool that executes tasks in a fixed number of worker threads.
Definition ThreadPool.h:45
ResultThreading waitForTask(Task &task)
Blocks until this task's function finishes and its node is released, before its optional notification...
ResultThreading destroy()
Destroy the thread pool created previously with ThreadPool::create.
ResultThreading waitForAllTasks()
Blocks execution until all queued tasks and their afterRelease notifications have completed.
ResultThreading create(size_t workerThreads)
Create a thread pool with the requested number of worker threads.
ResultThreading queueTask(Task &task)
Queue a task (that should not be already in use)