Repository navigation
Expand file tree
/
Copy paththreadpool.hpp
More file actions
109 lines (92 loc) · 1.96 KB
/
Copy paththreadpool.hpp
File metadata and controls
109 lines (92 loc) · 1.96 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
#pragma once
#include <chrono>
#include <vector>
#include <deque>
#include <functional>
#include <future>
#include <thread>
#include <condition_variable>
#include <algorithm>
using std::condition_variable;
using std::deque;
using std::function;
using std::future;
using std::mutex;
using std::packaged_task;
using std::thread;
using std::unique_lock;
using std::vector;
class threadpool
{
using pool_type = vector<thread>;
using tasks_type = deque<function<void()>>;
using size_type = pool_type::size_type;
bool running = true;
mutex access;
condition_variable condition;
tasks_type tasks;
pool_type pool;
public:
explicit threadpool(size_type thread_amount)
{
assert(thread_amount > 0);
while (thread_amount --> 0)
{
create_thread();
}
}
#define IMPL(PTR, LAMBDA) \
auto future = (PTR)->get_future(); \
unique_lock<mutex> lock(access); \
tasks.push_back(LAMBDA); \
condition.notify_one(); \
return std::move(future);
template<typename Ret>
auto push(packaged_task<Ret()>& task) -> future<Ret>
{
IMPL(&task, [&task]{task();});
}
template<typename Func, typename... Args>
auto push(const Func& func, Args... args) -> future< decltype(func(args...)) >
{
const auto ptr = new packaged_task<Func>(func);
IMPL(ptr, ([ptr, args...] { (*ptr)(args...); delete ptr; }) );
}
#undef IMPL
~threadpool(void)
{
running = false;
condition.notify_all();
for (auto &thread : pool)
{
thread.join();
}
pool.clear();
}
private:
inline void create_thread(void)
{
auto start = [this](void)
{
while (running)
{
function<void()> task;
{
unique_lock<mutex> lock(access);
if (tasks.empty())
{
condition.wait(lock);
continue;
}
task = std::move(tasks.front());
tasks.pop_front();
}
task();
}
};
thread thread(start);
pool.push_back(std::move(thread));
}
threadpool(const threadpool&) = delete;
threadpool& operator=(const threadpool&) = delete;
};