2021-10-12 14:20:30 +02:00
|
|
|
#pragma once
|
2023-12-17 16:16:46 +01:00
|
|
|
#include "Containers/Array.h"
|
2021-10-23 00:22:35 +02:00
|
|
|
#include "Containers/List.h"
|
2024-06-09 12:20:04 +02:00
|
|
|
#include <functional>
|
|
|
|
|
#include <thread>
|
2021-10-12 14:20:30 +02:00
|
|
|
|
2024-06-09 12:20:04 +02:00
|
|
|
namespace Seele {
|
|
|
|
|
class ThreadPool {
|
|
|
|
|
public:
|
2024-10-01 22:52:51 +02:00
|
|
|
ThreadPool(uint32 numWorkers = std::thread::hardware_concurrency() - 2);
|
2023-12-17 16:16:46 +01:00
|
|
|
~ThreadPool();
|
2024-05-23 14:58:14 +02:00
|
|
|
void runAndWait(List<std::function<void()>> functions);
|
2024-07-15 08:32:50 +02:00
|
|
|
void runAsync(std::function<void()> func);
|
2024-08-30 09:29:41 +02:00
|
|
|
void waitIdle();
|
2024-06-09 12:20:04 +02:00
|
|
|
private:
|
2024-07-18 11:45:56 +02:00
|
|
|
struct TaskGroup {
|
2023-12-17 16:16:46 +01:00
|
|
|
uint64 numRemaining = 0;
|
|
|
|
|
};
|
2024-07-18 11:45:56 +02:00
|
|
|
struct QueueEntry {
|
|
|
|
|
std::function<void()> func;
|
|
|
|
|
TaskGroup* task = nullptr;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
std::mutex queueLock;
|
|
|
|
|
std::condition_variable queueCV;
|
2024-08-30 09:29:41 +02:00
|
|
|
std::atomic_uint32_t numWaiting = 0;
|
|
|
|
|
std::condition_variable idleCV;
|
2024-07-18 11:45:56 +02:00
|
|
|
List<QueueEntry> queue;
|
|
|
|
|
|
2023-12-17 16:16:46 +01:00
|
|
|
void work();
|
2022-03-19 22:45:30 +01:00
|
|
|
Array<std::thread> workers;
|
2024-07-18 11:45:56 +02:00
|
|
|
|
2023-12-17 16:16:46 +01:00
|
|
|
std::mutex taskLock;
|
|
|
|
|
std::condition_variable completedCV;
|
2024-07-18 11:45:56 +02:00
|
|
|
List<TaskGroup> runningTasks;
|
2023-12-17 16:16:46 +01:00
|
|
|
bool running = true;
|
2021-12-15 00:05:42 +01:00
|
|
|
};
|
2024-05-01 19:05:48 +02:00
|
|
|
ThreadPool& getThreadPool();
|
2024-06-09 12:20:04 +02:00
|
|
|
} // namespace Seele
|