-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread_pool.cpp
44 lines (38 loc) · 880 Bytes
/
thread_pool.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
#include <thread_pool.hpp>
void ThreadPool::ThreadLoop()
{
std::function<void()> task;
while (true)
{
{
std::unique_lock<std::mutex> lock(mutex_);
cv.wait(lock);
if (task_queue_.empty())
{
return;
}
task = std::move(task_queue_.front());
task_queue_.pop();
}
task();
}
}
ThreadPool::ThreadPool(uint32_t thread_count) {
for (uint32_t i = 0; i < thread_count; i++)
{
threads_.push_back(std::thread(&ThreadPool::ThreadLoop,this));
}
}
ThreadPool::~ThreadPool(){
{
const std::scoped_lock<std::mutex> lock(mutex_);
while(!task_queue_.empty()){
task_queue_.pop();
}
}
cv.notify_all();
for(auto& thread : threads_) {
thread.join();
}
threads_.clear();
}