-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreadPool.cpp
75 lines (66 loc) · 1.29 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "ThreadPool.hpp"
void ThreadPool::ThreadPool::setupThreadPool(u64 thread_count)
{
threads_.clear();
for (u64 i = 0; i < thread_count; ++i)
threads_.push_back(std::jthread([&]() { workerLoop(); }));
}
void ThreadPool::ThreadPool::workerLoop()
{
std::function<void()> job;
while (not halt_) {
{
std::unique_lock lock(job_mutex_);
condition_.wait(lock, [this]()
{
return not jobs_.empty() or halt_;
});
if (halt_) return;
job = jobs_.front();
jobs_.pop();
}
job();
}
}
ThreadPool::ThreadPool::ThreadPool(u64 threadCount)
{
setupThreadPool(threadCount);
}
ThreadPool::ThreadPool::~ThreadPool()
{
halt();
join();
}
void ThreadPool::ThreadPool::join()
{
for (auto& thread : threads_)
if (thread.joinable())
{
condition_.notify_all();
thread.join();
}
threads_.clear();
}
u64 ThreadPool::ThreadPool::getThreadCount() const
{
return threads_.size();
}
void ThreadPool::ThreadPool::dropUnstartedJobs()
{
halt();
join();
std::queue<std::function<void()>> empty;
std::swap(jobs_, empty);
setupThreadPool(threads_.size());
}
void ThreadPool::ThreadPool::halt()
{
halt_ = true;
condition_.notify_all();
for (auto& thread : threads_)
thread.request_stop();
}
void ThreadPool::ThreadPool::start(u64 threadCount)
{
setupThreadPool(threadCount);
}