-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.cpp
More file actions
56 lines (44 loc) · 1.59 KB
/
Copy pathThreadPool.cpp
File metadata and controls
56 lines (44 loc) · 1.59 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
#include "ThreadPool.hpp"
ThreadPool::ThreadPool(int threadCount) : threadCount(threadCount), stop(false) {
for (int i = 0; i < threadCount ; i++){
workers.emplace_back([this](){
while(true){
std::unique_lock<std::mutex> lock(this->mutex);
//Wait again if the not finishes
this->cv.wait(lock,[this]() {
return this->stop || !this->tasks.empty();
});
// woken up but no tasks or program finished?
if (this->stop && this->tasks.empty()) {
return;
}
// we use move to avoid creating intermediate object by directly transfering ownership
// ****
std::function<void()> task = std::move(tasks.front());
tasks.pop();
lock.unlock();
task();
}
});
}
}
ThreadPool::~ThreadPool(){
//if we dont lock before write the value(though it will only be modified by main thread)
// the value store on the cache will not be pushed to the ram, so other threads wont notice it changed
std::unique_lock<std::mutex> lock(this->mutex);
this->stop = true;
lock.unlock();
cv.notify_all();
for(auto & worker : workers){
if (worker.joinable()) {
worker.join();
}
}
}
void ThreadPool::queuTask(std::function<void()> task){
std::unique_lock<std::mutex> lock(this->mutex);
// same strategy than ****
tasks.push(std::move(task));
lock.unlock();
this->cv.notify_one();
}