-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththread_pool.cpp
More file actions
40 lines (37 loc) · 1.03 KB
/
Copy paththread_pool.cpp
File metadata and controls
40 lines (37 loc) · 1.03 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
#include "thread_pool.h"
ThreadPool::ThreadPool(size_t thread_num){
for(int i=0;i<thread_num;i++){
workers.emplace_back([this](){
while(1){
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(_mutex);
//判断任务队列是否为空以及线程池是否关闭
condition.wait(lock,[this](){
return stop_pool || tasks.empty();
});
task = std::move(tasks.front());
tasks.pop();
}
task();
}
}
);
}
}
void ThreadPool::add_task(std::function<void()> task){
{
std::unique_lock<std::mutex> lock(_mutex);
tasks.push(std::move(task));
}
condition.notify_one();
}
ThreadPool::~ThreadPool(){
{
std::unique_lock<std::mutex> lock(_mutex);
stop_pool = true;
}
for(auto& worker:workers){
worker.join();
}
}