-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_pool.cpp
More file actions
67 lines (61 loc) · 1.73 KB
/
thread_pool.cpp
File metadata and controls
67 lines (61 loc) · 1.73 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
#include "thread_pool.h"
namespace pool {
ThreadPool::Worker::Worker(ThreadPool& pool)
: Pool(pool)
{
Pool.WaitsTask.notify_one();
}
void ThreadPool::Worker::operator()() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(Pool.Mutex);
Pool.HasTask.wait(lock, [this]() {
return !Pool.Working || !Pool.Tasks.empty();
});
if (!Pool.Working && Pool.Tasks.empty()) {
return;
}
task = std::move(Pool.Tasks.front());
Pool.Tasks.pop();
}
task();
Pool.WaitsTask.notify_one();
}
}
ThreadPool::ThreadPool(size_t poolSize)
: Working(true)
{
Workers.reserve(poolSize);
for (size_t i = 0; i < poolSize; ++i) {
Workers.emplace_back(Worker(*this));
}
ManageThread = std::thread(&ThreadPool::ManageTasks, this);
}
void ThreadPool::ManageTasks() {
while (true)
{
std::unique_lock<std::mutex> lock(Mutex);
WaitsTask.wait(lock, [this]() {
return !Working || !Tasks.empty();
});
if (!Working) {
return;
} else if (!Tasks.empty()) {
HasTask.notify_one();
}
}
}
ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(Mutex);
Working = false;
}
HasTask.notify_all();
WaitsTask.notify_all();
for (auto& worker : Workers) {
worker.join();
}
ManageThread.join();
}
}