-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy paththreadpool.hpp
More file actions
79 lines (65 loc) · 1.39 KB
/
threadpool.hpp
File metadata and controls
79 lines (65 loc) · 1.39 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
/*
* This file is licensed under the zlib/libpng license, included in this
* distribution in the file COPYING.
*/
#include <future>
#include <thread>
#include <deque>
#include <vector>
#include <utility>
#include <chrono>
#include <functional>
#include <type_traits>
#ifndef WORKQUEUE_threadpool_hpp
#define WORKQUEUE_threadpool_hpp
namespace workqueue {
class threadpool {
std::vector<std::thread> pool;
bool stop;
std::mutex access;
std::condition_variable cond;
std::deque<std::function<void()>> tasks;
public:
explicit threadpool(int nr = 1) : stop(false) {
while(nr-->0) {
add_worker();
}
}
~threadpool() {
stop = true;
for(std::thread &t : pool) {
t.join();
}
pool.clear();
}
template<class Rt>
auto add_task(std::packaged_task<Rt()>& pt) -> std::future<Rt> {
std::unique_lock<std::mutex> lock(access);
auto ret = pt.get_future();
tasks.push_back([&pt]{pt();});
cond.notify_one();
return ret;
}
private:
void add_worker() {
std::thread t([this]() {
while(!stop) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(access);
if(tasks.empty()) {
cond.wait_for(lock, std::chrono::duration<int, std::milli>(5));
continue;
}
task = std::move(tasks.front());
tasks.pop_front();
}
task();
}
});
pool.push_back(std::move(t));
}
};
}
#endif//WORKQUEUE_threadpool_hpp
// vim: syntax=cpp11