Hubris Engine Dev
A Project to learn and get into Game Engine developement.
 
Loading...
Searching...
No Matches
ThreadPool.h
Go to the documentation of this file.
1#pragma once
2#include <vector>
3#include <atomic>
4#include <condition_variable>
5#include <mutex>
6#if defined(__GNUC__) || defined(__clang__)
7// GCC/Clang specific
8#include <x86intrin.h> // or <arm_neon.h> depending on architecture
9#elif defined(_MSC_VER)
10// MSVC specific
11#include <intrin.h>
12#endif
13
14#include <atomic>
15#include <condition_variable>
16#include <thread>
17#include <functional>
18
19namespace Hubris {
20 class WaitGroup final {
21 private:
22 std::atomic<int> count{ 0 }; // Counter for tracking the number of tasks
23 std::mutex mtx; // Mutex for coordinating condition variable
24 std::condition_variable cv; // Condition variable for wait signaling
25 std::atomic<bool> waiting{ false }; // Flag to prevent multiple waits
26 public:
27 WaitGroup() = default;
28
29 // Increment the counter
30 void Add(int n) {
31 count.fetch_add(n, std::memory_order_relaxed);
32 }
33
34 // Decrement the counter and notify waiting threads if it reaches zero
35 void Done() {
36 if (count.fetch_sub(1, std::memory_order_acq_rel) == 1) {
37 std::lock_guard<std::mutex> lock(mtx);
38 cv.notify_all(); // Notify waiting threads
39 }
40 }
41
42 // Wait for the counter to reach zero, usually called by the main thread
43 void Wait() {
44 bool expected = false;
45 if (!waiting.compare_exchange_strong(expected, true)) {
46 throw std::runtime_error("Only one thread can wait at a time.");
47 }
48 std::unique_lock<std::mutex> lock(mtx);
49 cv.wait(lock, [&] { return count.load(std::memory_order_acquire) == 0; });
50
51 // Reset the waiting flag after the wait is done, out of precaution.
52 waiting.store(false, std::memory_order_release);
53 }
54 };
55
56
57
58 class ThreadPool final {
59 private:
63 static inline unsigned int ThreadCount;
67 static inline std::vector<std::thread> Threads;
68 public:
69 static void InitalizePool(unsigned int threadCount = std::thread::hardware_concurrency() - 1) {
70 ThreadCount = std::min(threadCount, std::thread::hardware_concurrency() - 1);
71 Logger::Log("{} Threads Allocated", ThreadCount);
72 for (unsigned int i = 0; i < ThreadCount; i++) {
73 Threads.emplace_back([]() {
74 while (true) {
75 // Wait for a task to be assigned
76 // Execute the task
77 }
78 });
79 }
80 }
81
91 static void QueueJob(WaitGroup* wg, std::function<void()> job){
92
93 }
94 };
95}
static void Log(const char *message)
Definition Logger.h:104
static void InitalizePool(unsigned int threadCount=std::thread::hardware_concurrency() - 1)
Definition ThreadPool.h:69
static void QueueJob(WaitGroup *wg, std::function< void()> job)
Queues a job to be executed by the threadpool, it may get executed by any thread in the pool.
Definition ThreadPool.h:91
WaitGroup()=default
void Add(int n)
Definition ThreadPool.h:30
The Hubris Engine main namespace.
Definition EventBus.h:4