-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.h
More file actions
80 lines (74 loc) · 2.16 KB
/
Copy pathThreadPool.h
File metadata and controls
80 lines (74 loc) · 2.16 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
#include <iostream>
#include <queue>
#include <vector>
#include <thread>
#include <mutex>
using namespace std;
class ThreadPool
{
int workers;
queue<function<void()>> tasks;
vector<thread> threads;
mutex m;// this is to ensure synchronous or unique access to a shared resource
condition_variable cv;// this helps prevent the busy waiting and replace it with the sleep mechanism
bool stop; // this one is to indicate that the program is finished so that all threads can be joined and then the program gets terminated after all the threads being closed
void lookup()
{
function<void()> task;
while (true)
{
//in this part we would need to lock and unlock the internally for conditional variable so we need unique lock ..
unique_lock<mutex> lock(m);
{
cout<<"looking\n";
cv.wait(lock, [&]
{ return stop || !tasks.empty(); });
if (stop && tasks.empty())
return;
task = std::move(tasks.front());
tasks.pop();
}
task();
}
}
public:
ThreadPool()
{
this->workers = 1;
this->stop=false;
}
ThreadPool(int workers)
{
this->workers = workers;
this->stop=false;
for(int i=0;i<workers;i++)
{
threads.emplace_back([this] {
lookup();
});
}
}
void addToPool(function<void()> task)
{
//this lock can't be manually unlocked it would be automatically unlocked once the program goes out of scope
//we could have also use the unique_lock here but it would be heavier
// unique_lock<mutex> lock(m);
lock_guard<mutex> lock(m);
tasks.push(task);
cv.notify_one();
}
~ThreadPool()
{
{
lock_guard<mutex> lock(m);
stop=true;
}
//comment out the notify_all() to see what happens and try to explain why
// cv.notify_all();
for(auto &t:threads)
{
if (t.joinable())
t.join();
}
}
};