-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.h
More file actions
108 lines (82 loc) · 1.9 KB
/
Copy pathThreadPool.h
File metadata and controls
108 lines (82 loc) · 1.9 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
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
#ifndef HTTPSERVER_THREADPOOL_H
#define HTTPSERVER_THREADPOOL_H
#include "Mutex.h"
#include "MutexLockGuard.h"
#include "ConditionVar.h"
#include "Thread.h"
#include "Logger.h"
#include <queue>
#include <iostream>
using namespace std;
template <class T>
class ThreadPool {
public:
ThreadPool(int threadNum);
~ThreadPool();
static void* threadFunc(void* arg);
void run();
void start();
void submit(T* task);
void quit();
private:
// 是否停止线程池
bool stop_;
// 用于保护任务队列
Mutex mtx_;
ConditionVar cond_;
// 任务队列
std::queue<T*> taskQueue_;
// 工作线程
int threadNum_;
Thread* workers_;
};
template <class T>
ThreadPool<T>::ThreadPool(int threadNum) : threadNum_(threadNum), stop_(true) {}
template <class T>
ThreadPool<T>::~ThreadPool() {
delete []workers_;
}
template <class T>
void* ThreadPool<T>::threadFunc(void* arg) {
ThreadPool* mine = (ThreadPool*)arg;
mine->run();
}
template <class T>
void ThreadPool<T>::start() {
stop_ = false;
workers_ = new Thread[threadNum_];
for (int i = 0; i < threadNum_; i++) {
workers_[i].setFunc(threadFunc, this);
workers_[i].start();
LOG_INFO("The %d thread start!", i);
}
}
template <class T>
void ThreadPool<T>::run() {
LOG_INFO("thread start running!");
while (!stop_) {
T* item;
{
MutexLockGuard guard(mtx_);
while (taskQueue_.empty()) {
cond_.wait(mtx_);
}
item = taskQueue_.front();
taskQueue_.pop();
}
item->process();
}
}
template <class T>
void ThreadPool<T>::submit(T* item) {
MutexLockGuard guard(mtx_);
taskQueue_.push(item);
cond_.signal();
}
template <class T>
void ThreadPool<T>::quit() {
MutexLockGuard guard(mtx_);
stop_ = true;
cond_.signalAll();
}
#endif