-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreadpool.h
73 lines (57 loc) · 1.76 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
//
// Created by elle on 05/06/21.
//
#ifndef LAB6_THREADPOOL_H
#define LAB6_THREADPOOL_H
#include <future>
#include <vector>
#include <queue>
using task_t = std::packaged_task<void()>;
class thread_pool {
std::vector<std::thread> workers;
std::queue<task_t> tasks;
std::mutex m;
std::condition_variable cv;
int N; // number of threads
bool stop;
public:
explicit thread_pool(const int &N = std::thread::hardware_concurrency());
void enqueue(task_t task);
~thread_pool();
};
thread_pool::thread_pool(const int &N) : N(N), stop(false) {
for(int i = 0; i < N ; ++i)
// creating the N threads
workers.emplace_back(
[this](){
while(!stop || !tasks.empty()){
std::unique_lock ul{m};
// "sleep" until a new task needs to get executed
// or if stop signal received
cv.wait(ul, [this]() { return !tasks.empty() || stop ; });
if( !tasks.empty()) { // something to do!
task_t task = std::move(tasks.front());
tasks.pop();
ul.unlock(); // release the lock
task();
ul.lock(); // get the lock again
}
}
});
}
thread_pool::~thread_pool(){
{
std::unique_lock ul{m};
stop = true;
}
cv.notify_all();
for(auto &t : workers) t.join();
}
void thread_pool::enqueue(task_t t) {
std::unique_lock ul{m};
if (stop)
throw std::logic_error("can't enqueue after stop signal");
tasks.push(std::move(t));
cv.notify_one();
}
#endif //LAB6_THREADPOOL_H