/
pool.hpp
258 lines (227 loc) · 6.18 KB
/
pool.hpp
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#ifndef THREADPOOL_POOL_H
#define THREADPOOL_POOL_H
#include <condition_variable>
#include <future>
#include <list>
#include <queue>
#include "worker_thread.hpp"
namespace threadpool {
/*
* Thread pool that does not need a master thread to manage load. A task is of
* the form std::function<T(void)>, and the add_task() function will return a
* std::future<T> which will contain the return value of the function. Tasks are
* placed in a queue. Threads are created only when there are no idle threads
* available and the total thread count does not exceed the maximum thread
* count. Threads are despawned if they are idle for more than despawn_file_ms,
* the third argument in the constructor of the threadpool.
*/
class pool
{
public:
/*
* Creates a new thread pool, with max_threads threads allowed. Starts paused
* if start_paused = true. Default values are max_threads =
* std::thread::hardware_concurrency(), which should return the number of
* physical cores the CPU has, start_paused = false, and idle_time = 1000.
*/
pool(unsigned int max_threads = std::thread::hardware_concurrency(),
bool start_paused = false,
unsigned int idle_time = 1000)
: max_threads(max_threads),
idle_time(idle_time),
threads_created(0),
threads_running(0),
join_requested(false),
paused(start_paused)
{
if (start_paused)
{
pause();
}
}
/*
* When the pool is destructed, it will first stop all worker threads.
*/
~pool()
{
join();
}
/*
* Adds a new task to the task queue. The task must be a function object,
* and the remaining passed arguments must be parameters for task, which will
* be bound using std::bind().
*/
template <typename T, typename... Args,
typename R = typename std::result_of<T(Args...)>::type>
std::future<R> add_task(T&& task, Args&&... args)
{
/*
* If all created threads are executing tasks and we have not spawned the
* maximum number of allowed threads, create a new thread.
*/
if (threads_created == threads_running && threads_created != max_threads)
{
std::lock_guard<std::mutex> thread_lock(thread_mutex);
threads.emplace_back(std::bind(&pool::run_task, this));
}
auto p_task = std::make_shared<std::packaged_task<R()>>(
std::bind(std::forward<T>(task), std::forward<Args>(args)...));
{
std::lock_guard<std::mutex> task_lock(task_mutex);
tasks.emplace([p_task] { (*p_task)(); });
}
task_ready.notify_one();
return p_task->get_future();
}
/*
* Clears the task queue. Does not stop any running tasks.
*/
void clear()
{
std::lock_guard<std::mutex> task_lock(task_mutex);
std::queue<std::function<void(void)>>().swap(tasks);
}
/*
* Returns true if the task queue is empty. Note that worker threads may be
* running, even if empty() returns true.
*/
bool empty()
{
std::lock_guard<std::mutex> task_lock(task_mutex);
return tasks.empty();
}
/*
* Waits for all threads to finish executing. All worker threads will exit.
*/
void join()
{
join_requested = true;
task_ready.notify_all();
unpause();
{
std::lock_guard<std::mutex> thread_lock(thread_mutex);
for (auto&& thread : threads)
{
thread.join();
}
threads.clear();
}
join_requested = false;
}
/*
* Pauses the thread pool - all currently executing tasks will finish, but any
* remaining tasks in the task queue will not be executed until unpause() is
* called. Tasks may still be added to the queue when the pool is paused.
* Any spawned threads will not despawn.
*/
void pause()
{
paused = true;
}
void unpause()
{
paused = false;
unpaused_cv.notify_all();
}
/*
* Waits for the task queue to empty and for all worker threads to complete,
* without destroying worker threads.
*/
void wait(bool clear_tasks = false)
{
if (clear_tasks)
{
clear();
}
std::unique_lock<std::mutex> lck(task_mutex);
task_empty.wait(lck, [&] { return tasks.empty() && !threads_running; });
}
unsigned int get_threads_running() const
{
return threads_running.load();
}
unsigned int get_threads_created() const
{
return threads_created.load();
}
unsigned int get_max_threads() const
{
return max_threads;
}
void set_max_threads(unsigned int max_threads)
{
this->max_threads = max_threads;
}
unsigned int get_idle_time() const
{
return idle_time.count();
}
void set_idle_time(unsigned int idle_time)
{
this->idle_time = std::chrono::milliseconds(idle_time);
}
private:
std::function<void(void)> pop_task()
{
std::function<void(void)> ret;
std::unique_lock<std::mutex> task_lock(task_mutex);
if (idle_time.count() > 0)
{
task_ready.wait_for(task_lock, idle_time,
[&]{ return join_requested || !tasks.empty(); });
}
else
{
task_ready.wait(task_lock,
[&]{ return join_requested || !tasks.empty(); });
}
if (!tasks.empty())
{
ret = tasks.front();
tasks.pop();
}
return ret;
}
void run_task()
{
++threads_created;
while (threads_created <= max_threads)
{
{
std::unique_lock<std::mutex> lck(pause_mutex);
unpaused_cv.wait(lck, [&] { return !paused; });
}
if (auto t = pop_task())
{
++threads_running;
t();
--threads_running;
if (!threads_running && empty())
{
task_empty.notify_all();
}
}
else
{
break;
}
}
--threads_created;
if (std::unique_lock<std::mutex>(thread_mutex, std::try_to_lock))
{
threads.remove_if([] (const worker_thread& thread) {
return !thread.running;
});
}
}
std::list<worker_thread> threads;
std::queue<std::function<void(void)>> tasks;
std::mutex task_mutex, thread_mutex, pause_mutex;
std::condition_variable_any task_ready, task_empty, unpaused_cv;
unsigned int max_threads;
std::chrono::milliseconds idle_time;
std::atomic<unsigned int> threads_created, threads_running;
std::atomic<bool> join_requested, paused;
};
}
#endif //THREADPOOL_POOL_H