-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThread.h
More file actions
72 lines (58 loc) · 1.29 KB
/
Copy pathThread.h
File metadata and controls
72 lines (58 loc) · 1.29 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
#pragma once
#include <thread>
#include <functional>
#include <iostream>
#include <queue>
#include <atomic>
#include <mutex>
class ThreadPool {
int numThreads;
std::vector<std::thread> threads;
std::queue<std::function<void()>> tasks;
std::mutex mtx;
std::mutex idle;
std::condition_variable condition;
std::atomic<int> numTask = 0;
bool shutdown = false;
public:
ThreadPool(int numThreads) :numThreads(numThreads) {
for (int i = 0; i < numThreads; i++) {
threads.emplace_back([this, i] {
while (true) {
std::unique_lock<std::mutex> lock(mtx);
condition.wait(lock, [this] {return !tasks.empty() || shutdown; });
if (shutdown)break;
auto task(std::move(tasks.front()));
tasks.pop();
lock.unlock();
task();
numTask--;
}
});
}
}
~ThreadPool() {
mtx.lock();
shutdown = true;
mtx.unlock();
condition.notify_all();
for (int i = 0; i < numThreads; i++) {
threads[i].join();
}
}
template<class F, class ...Args>
void addTask(F&& f, Args&&... args) {
std::function<void()>task = std::bind(std::forward<F>(f), std::forward<Args>(args)...);
mtx.lock();
numTask++;
tasks.emplace(std::move(task));
mtx.unlock();
condition.notify_one();
}
void barrier() {
while (numTask > 0) {
idle.lock();
idle.unlock();
}
}
};