-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathThreadPool.cpp
More file actions
134 lines (122 loc) · 1.94 KB
/
Copy pathThreadPool.cpp
File metadata and controls
134 lines (122 loc) · 1.94 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <exception>
#include <stdio.h>
#include <stdlib.h>
#include "ThreadPool.h"
using namespace xnet;
ThreadPool::ThreadPool(const std::string& name) :
name_(name),
maxQueueSize_(0),
running_(false)
{
}
ThreadPool::~ThreadPool()
{
if (running_)
{
stop();
}
}
void ThreadPool::stop()
{
{
MutexLockGuard lock(mutex_);
running_ = false;
notEmpty_.notify_all();
}
for (auto& thread : threads_)
{
thread->join();
}
}
void ThreadPool::start(int numThreads)
{
running_ = true;
threads_.reserve(numThreads);
for (int i = 0; i < numThreads; i++)
{
ThreadPtr pThread = std::make_shared<Thread>(std::bind(&ThreadPool::runInThread, this));
pThread->start();
threads_.push_back(pThread);
}
}
void ThreadPool::run(const Task& task)
{
if (threads_.empty())
{
task();
}
else
{
MutexLockGuard lock(mutex_);
while (isFull())
{
notFull_.wait(lock);
}
queue_.push_back(task);
notEmpty_.notify_one();
}
}
void ThreadPool::run(Task&& task)
{
if(threads_.empty())
{
task();
}
else
{
MutexLockGuard lock(mutex_);
while(isFull())
{
notFull_.wait(lock);
}
queue_.push_back(std::move(task));
notEmpty_.notify_one();
}
}
void ThreadPool::runInThread()
{
try{
while (running_)
{
Task task = take();
if (task)
{
task();
}
}
}
catch(const std::exception& ex)
{
fprintf(stderr, "exception caught in ThreadPool %s\n", name_.data());
fprintf(stderr, "reason: %s\n", ex.what());
abort();
}
catch(...)
{
fprintf(stderr, "Unknown exception caught in ThreadPool %s\n", name_.data());
throw;
}
}
ThreadPool::Task ThreadPool::take()
{
MutexLockGuard lock(mutex_);
while (queue_.empty() && running_)
{
notEmpty_.wait(lock);
}
Task task;
if (!queue_.empty())
{
task = queue_.front();
queue_.pop_front();
if (maxQueueSize_ > 0)
{
notFull_.notify_one();
}
}
return task;
}
bool ThreadPool::isFull() const
{
return maxQueueSize_ > 0 && queue_.size() >= maxQueueSize_;
}