-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_pool.h
More file actions
162 lines (137 loc) · 4.15 KB
/
thread_pool.h
File metadata and controls
162 lines (137 loc) · 4.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <thread>
#include <vector>
#include <queue>
#include <functional>
#include <future>
#include <condition_variable>
#include <iostream>
#include <memory>
#include <atomic>
struct TPTaskQueue {
std::queue<std::function<void()>> tasks;
std::mutex mutex;
std::condition_variable cv;
std::atomic<int> taskCount{0};
std::atomic<bool> shutdown{false};
void addTask(std::function<void()> task) {
{
std::lock_guard<std::mutex> lock(mutex);
tasks.push(std::move(task));
taskCount++;
}
cv.notify_one();
}
bool getTask(std::function<void()>& task) {
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [this] { return !tasks.empty() || shutdown; });
if (shutdown && tasks.empty()) {
return false;
}
if (!tasks.empty()) {
task = std::move(tasks.front());
tasks.pop();
taskCount--;
return true;
}
return false;
}
void requestShutdown() {
shutdown = true;
cv.notify_all();
}
void waitForAll() {
while (taskCount > 0) {
std::this_thread::yield();
}
}
};
struct TPThread{
int id;
std::thread cur_thread;
std::function<void()> task;
TPTaskQueue* taskQueue;
TPThread(int id, TPTaskQueue* queue) : id(id), taskQueue(queue) {
cur_thread = std::thread([this]() { run(); });
}
void run(){
while(true){
if (!taskQueue->getTask(task)) {
break; // Shutdown requested
}
if(task){
try {
task();
} catch (const std::exception& e) {
std::cerr << "Task exception in thread " << id << ": " << e.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception in thread " << id << std::endl;
}
task = nullptr;
}
}
}
void stop(){
if(cur_thread.joinable()){
cur_thread.join();
}
}
};
class TPThreadPool {
private:
TPTaskQueue taskQueue;
std::vector<TPThread> threads;
int numThreads;
std::atomic<bool> destroyed{false};
public:
TPThreadPool(int n = std::thread::hardware_concurrency()) : numThreads(n) {
if (n <= 0) {
throw std::invalid_argument("Thread count must be positive");
}
threads.reserve(numThreads);
for(int i = 0; i < numThreads; ++i){
threads.emplace_back(i, &taskQueue);
}
}
~TPThreadPool(){
shutdown();
}
void shutdown() {
if (!destroyed.exchange(true)) {
taskQueue.requestShutdown();
for(auto& thread : threads){
thread.stop();
}
}
}
// Enqueue a task and get a future for its result
template<typename Func, typename... Args>
auto enqueue(Func&& f, Args&&... args) -> std::future<decltype(f(args...))> {
if (destroyed.load()) {
throw std::runtime_error("Cannot enqueue tasks on destroyed thread pool");
}
using ReturnType = decltype(f(args...));
auto task = std::make_shared<std::packaged_task<ReturnType()>>(
std::bind(std::forward<Func>(f), std::forward<Args>(args)...)
);
std::future<ReturnType> res = task->get_future();
taskQueue.addTask([task]() { (*task)(); });
return res;
}
void parallelFor(int start, int end, std::function<void(int)> func) {
if (start >= end) return;
std::vector<std::future<void>> futures;
futures.reserve(end - start);
for (int i = start; i < end; ++i) {
futures.push_back(enqueue(func, i));
}
// Wait for all tasks to complete
for (auto& future : futures) {
future.wait();
}
}
size_t getThreadCount() const { return numThreads; }
size_t getPendingTaskCount() const { return taskQueue.taskCount.load(); }
};
#endif // THREAD_POOL_H