-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadpool.h
More file actions
99 lines (86 loc) · 1.97 KB
/
threadpool.h
File metadata and controls
99 lines (86 loc) · 1.97 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
/*************************************************************************
> File Name: threadpool.cpp
> Author:jieni
> Mail:
> Created Time: 2020年07月24日 星期五 16时31分36秒
************************************************************************/
#include <list>
#include <functional>
#include "mutex.h"
#include "condition.h"
#include "socket.h"
typedef std::function<void(std::shared_ptr<conn>)> callback;
typedef struct task {
callback callback_;
std::shared_ptr<conn> conn_;
}Task;
class Threadpool {
public:
Threadpool();
~Threadpool();
bool push_back(Task);
static void *worker(void *arg);
void run();
private:
int numthreads;
int max_requests;
pthread_t *threads;
std::list<Task> workqueue;
MutexLock mutex;
Condition cond_;
};
Threadpool::Threadpool()
: numthreads(8),
cond_(mutex),
max_requests(100)
{
if ((numthreads <= 0) || (max_requests <= 0)) {
}
threads = new pthread_t[numthreads];
if (!threads) {
}
for(int i = 0; i < numthreads; i++) {
if ((pthread_create(threads + i, NULL, worker, this)) != 0) {
delete []threads;
}
if (pthread_detach(threads[i])) {
delete []threads;
}
}
}
Threadpool::~Threadpool()
{
delete [] threads;
}
bool Threadpool::push_back(Task task_)
{
{
MutexLockGuard lock(mutex);
if (workqueue.size() > max_requests)
return false;
workqueue.push_back(task_);
}
cond_.notify();
return true;
}
void *Threadpool::worker(void *arg)
{
Threadpool* pool = (Threadpool *)arg;
pool->run();
return pool;
}
void Threadpool::run()
{
while(1) {
mutex.lock();
while (workqueue.size() < 1) {
cond_.wait();
}
Task task_ = workqueue.front();
workqueue.pop_front();
mutex.unlock();
if(task_.callback_) {
task_.callback_(task_.conn_);
}
}
}