-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreadpool.cpp
121 lines (92 loc) · 2.06 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include "ThreadPool.h"
#include <iostream>
using namespace std;
ThreadPool::ThreadPool(int min,int max):m_maxThread(max),m_minThread(min),m_stop(false),m_idleThread(min),m_curThread(min)
{
m_manager = new thread(&ThreadPool::manager,this);
for(int i = 0;i<min;i++){
thread t(&ThreadPool::worker,this);
m_workers.insert(std::make_pair(t.get_id(),move(t)));
}
}
ThreadPool::manager(void){
while(!m_stop.load()){
this_thread::sleep_for(chrono::seconds(3));
int idel = m_idelThread.load();
int cur = m_curThread.load();
if(cur >minThread && idel >cur/2){
m_exitThread.store(2);
m_condition.notify_all();
}
lock_guard<mutex> lck(m_idsMutex);
if(!m_id.empty()){
for(auto id:m_id)
{
auto it = m_workers.find(id);
if(it != m_workers.end()){
(*it).second.join();
m_workers.erase(it);
}
}
}
else if(idel ==0 && cur < m_maxThread){
thread t(ThreadPool::worker,this);
m_workers.insert(make_pair(t.get_id(),move(t)));
m_curThread++;
m_idleThread++;
}
}
}
ThreadPool::worker(void){
while(!m_stop.load())
{
function<void(void)> task = nullptr;
unique_lock<mutex> locker(m_queueMutex);
while(m_tasks.empty() && !m_stop){
m_condition.wait(locker);
if(m_exitThread>0){
m_exitThread--;
m_curThread--;
lock_guard<mutex> lck(m_idsMutex);
m_id.emplace_back(this_thread::get_id());
return;
}
}
if(!m_tasks.empty()){
cout << "取出了一个任务" << endl;
task = move(m_tasks.front());
m_tasks.pop_front();
}
if(task){
m_idleThread--;
task();
m_idleThread++;
}
}
}
void ThreadPool::addTask(function<void(void)>task)
{
{
lock_guard<mutex> locker(m_queueMutex);
m_tasks.emplace_back(task);
}
m_condition.notify_one();
}
ThreadPool::~ThreadPool()
{
m_stop = true;
m_condition.notify_all();
for(auto it : m_workers)
{
thread& t = it.second;
if(t.joinable())
{
t.join();
cout << "线程" << t.get_id() << "将要退出了" << endl;
}
}
if(m_manager->joinable()){
m_manager->join();
}
delete m_manager;
}