-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadPool.cpp
54 lines (40 loc) · 1.02 KB
/
ThreadPool.cpp
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
#include "ThreadPool.h"
uint8_t const ThreadPool::CPU_CORE_COUNT = std::thread::hardware_concurrency();
uint8_t const ThreadPool::MAX_THREAD_COUNT = CPU_CORE_COUNT - 1;
void ThreadPool::start() {
if (_running) {
return;
}
_running = true;
for (uint8_t i = 0; i < MAX_THREAD_COUNT; ++i) {
addThread();
}
}
void ThreadPool::stop() {
if (!_running) {
return;
}
_running = false;
_event.signalAll();
for (auto &worker : _workers) {
if (worker.joinable()) {
worker.join();
}
}
_workers.clear();
}
void ThreadPool::addThread() {
assert(_workers.size() < MAX_THREAD_COUNT);
auto workerLoop = [this]() {
while (_running) {
Task task = nullptr;
if (_tasks.try_dequeue(task)) {
task();
} else {
// Double Check
_event.wait();
}
}
};
_workers.emplace_back(workerLoop);
}