-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadPool.hpp
86 lines (71 loc) · 2.18 KB
/
ThreadPool.hpp
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
#ifndef SIMPLE_THREAD_POOL_H
#define SIMPLE_THREAD_POOL_H
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <functional>
#include <condition_variable>
class ThreadPool {
public:
using Task = std::function<void()>;
ThreadPool(uint8_t num_threads) {
threads.reserve(num_threads);
for (uint8_t i = 0; i < num_threads; ++i) {
threads.push_back(std::thread([this] { threadHandler(); }));
}
}
void queue(const Task& task) {
{
std::lock_guard<std::mutex> taskQueueLock(taskQueueMutex);
taskQueue.push(task);
}
stopPoolCV.notify_one();
}
void stopProcessing() {
{
std::lock_guard<std::mutex> taskQueueLock(taskQueueMutex);
shouldStop = true;
}
stopPoolCV.notify_all();
}
void waitForTasks() {
std::unique_lock<std::mutex> taskQueueLock(taskQueueMutex);
tasksWaitCV.wait(taskQueueLock, [this] { return taskQueue.empty() && tasksInProgress == 0; });
}
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
~ThreadPool() noexcept {
stopProcessing();
for (auto& thread: threads) {
thread.join();
}
}
private:
std::vector<std::thread> threads;
std::queue<Task> taskQueue;
std::mutex taskQueueMutex;
std::condition_variable stopPoolCV;
std::condition_variable tasksWaitCV;
bool shouldStop = false;
unsigned int tasksInProgress = 0;
void threadHandler() {
while (true) {
std::unique_lock<std::mutex> taskQueueLock(taskQueueMutex);
stopPoolCV.wait(taskQueueLock, [this] { return !taskQueue.empty() || shouldStop; });
if (!taskQueue.empty()) {
Task task = taskQueue.front();
taskQueue.pop();
++tasksInProgress;
taskQueueLock.unlock();
task();
taskQueueLock.lock();
--tasksInProgress;
tasksWaitCV.notify_one();
} else if (shouldStop) {
break;
}
}
}
};
#endif //SIMPLE_THREAD_POOL_H