-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreadPool.h
93 lines (78 loc) · 1.99 KB
/
threadPool.h
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
#ifndef THREADPOOL_H
#define THREADPOOL_H
#include <thread>
#include <vector>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <queue>
//See https://stackoverflow.com/questions/15752659/thread-pooling-in-c11
class threadPool{
public:
void start();
void queueJob(const std::function<void()>& job);
void stop();
bool busy();
int getQueueSize();
private:
bool shouldTerminate = false;
void threadLoop();
std::mutex queueMutex;
std::condition_variable mutexCondition;
std::vector<std::thread> threads;
std::queue<std::function<void()>> jobs;
};
void threadPool::start(){
const int numThreads = std::thread::hardware_concurrency();
threads.resize(numThreads);
for(int i = 0; i < numThreads; i++){
threads.at(i) = std::thread(&threadPool::threadLoop, this);
}
}
void threadPool::threadLoop() {
while(true){
std::function<void()> job;
{
std::unique_lock<std::mutex> lock(queueMutex);
mutexCondition.wait(lock, [this] {
return !jobs.empty() || shouldTerminate;
});
if(shouldTerminate){
return;
}
job = jobs.front();
jobs.pop();
}
job();
}
}
void threadPool::queueJob(const std::function<void()>& job){
{
std::unique_lock<std::mutex> lock(queueMutex);
jobs.push(job);
}
mutexCondition.notify_one();
}
bool threadPool::busy(){
bool poolBusy;
{
std::unique_lock<std::mutex> lock(queueMutex);
poolBusy = !jobs.empty();
}
return poolBusy;
}
void threadPool::stop(){
{
std::unique_lock<std::mutex> lock(queueMutex);
shouldTerminate = true;
}
mutexCondition.notify_all();
for(std::thread& activeThread : threads){
activeThread.join();
}
threads.clear();
}
int threadPool::getQueueSize(){
return jobs.size();
}
#endif