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_COMPILER_EXPORT ThreadPool;
11
15struct SC_COMPILER_EXPORT ThreadPoolTask
16{
17
19 private:
20 friend struct ThreadPool;
21 ThreadPool* threadPool = nullptr;
22 ThreadPoolTask* next = nullptr;
23};
24
37struct SC_COMPILER_EXPORT ThreadPool
38{
39 using Task = ThreadPoolTask;
40
41 ThreadPool() = default;
42 ~ThreadPool() { (void)destroy(); }
43
45 Result create(size_t workerThreads);
46
50
53
56
59
60 private:
61 Task* taskHead = nullptr; // Head of the FIFO linked list containing all threads
62 Task* taskTail = nullptr; // Tail of the FIFO linked list containing all threads
63
64 size_t numRunningTasks = 0; // How many tasks are running in this moment
65 size_t numWorkerThreads = 0; // How many worker threads exist in this pool (== 0 means uninitialized threadpool)
66
67 Mutex poolMutex; // Protects all ThreadPool members access from worker threads
68 ConditionVariable taskAvailable; // Signals to worker threads that there is a new queued task available
69 ConditionVariable taskCompleted; // Signals to threadpool that there is a new task that was completed
70
71 bool stopRequested = false; // Signals background threads to end their infinite task processing loop
72
73 struct WorkerThread;
74};
75
77} // namespace SC
struct SC_COMPILER_EXPORT Function
Wraps function pointers, member functions and lambdas without ever allocating.
Definition Function.h:19
A native OS condition variable.
Definition Threading.h:58
A native OS mutex to synchronize access to shared resources.
Definition Threading.h:23
An ascii string used as boolean result. SC_TRY macro forwards errors to caller.
Definition Result.h:13
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
Simple thread pool that executes tasks in a fixed number of worker threads.
Definition ThreadPool.h:38
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.