Repository navigation
Expand file tree
/
Copy paththreadPool.h
More file actions
59 lines (52 loc) · 1.42 KB
/
Copy paththreadPool.h
File metadata and controls
59 lines (52 loc) · 1.42 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
#include<vector>
#include<queue>
#include<functional>
#include<thread>
#include<mutex>
#include<condition_variable>
class ThreadPool {
public:
ThreadPool(size_t numThreads) : stop(false) {
for (size_t i{0}; i < numThreads; ++i) {
workers.emplace_back([this] {
while (true) {
std::unique_lock<std::mutex> lock(queueMutex);
condition.wait(lock, [this] {
return stop || !tasks.empty();
});
if (stop && tasks.empty()) {
break;
}
auto task = std::move(tasks.front());
tasks.pop();
lock.unlock();
task();
}
});
}
}
template<class F>
void enqueue(F&& task) {
{
std::lock_guard<std::mutex> lock(queueMutex);
tasks.emplace(std::forward<F>(task));
}
condition.notify_one();
}
~ThreadPool() {
{
std::lock_guard<std::mutex> lock(queueMutex);
stop = true;
}
condition.notify_all();
for (auto& worker : workers) {
worker.join();
}
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queueMutex;
std::condition_variable condition;
bool stop;
};