-
Notifications
You must be signed in to change notification settings - Fork 0
/
threadpool.h
116 lines (100 loc) · 2.96 KB
/
threadpool.h
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
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <tuple>
#include <queue>
#include <array>
#include <memory>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <future>
namespace internal {
class TaskI
{
public:
virtual ~TaskI() = default;
virtual void execute() = 0;
};
template <typename Fn, typename ...Args>
class PackagedTask : public TaskI {
using ret_type = std::result_of_t<Fn(Args...)>;
public:
PackagedTask(Fn&& fn, Args&& ...args)
: fn_(std::forward<Fn>(fn)), args_(std::forward<Args>(args)...)
{}
virtual void execute() override
{
prom_.set_value(std::apply(fn_, std::move(args_)));
}
std::future<ret_type> get_future()
{
return prom_.get_future();
}
private:
Fn fn_;
std::promise<ret_type> prom_;
std::tuple<Args...> args_;
};
template<typename Lambda, std::size_t... I>
std::array<std::thread, sizeof...(I)> make_workers_impl(const Lambda& value, std::index_sequence<I...>)
{
return {(static_cast<void>(I), std::thread(value))...};
}
template <std::size_t N, typename Lambda>
std::array<std::thread, N> make_workers(const Lambda& value)
{
return make_workers_impl(value, std::make_index_sequence<N>());
}
}
template <size_t N>
class ThreadPool {
public:
ThreadPool()
:
workers_(internal::make_workers<N>([this]() {
while (true)
{
std::unique_lock<std::mutex> lck(mtx_);
while (!exit_ and tasks_.empty())
condition_.wait(lck);
if (exit_ and tasks_.empty())
return;
auto task = std::move(tasks_.front());
tasks_.pop();
lck.unlock();
task->execute();
}
}))
{}
template<class Fn, class... Args>
auto enqueue(Fn&& fn, Args&&... args)
-> std::future<typename std::result_of_t<Fn(Args...)>>
{
using ret_type = typename std::result_of_t<Fn(Args...)>;
auto task = std::make_unique<internal::PackagedTask<Fn, Args...>>(std::forward<Fn>(fn), std::forward<Args>(args)...);
std::future<ret_type> ret = task->get_future();
{
std::lock_guard<std::mutex> lck(mtx_);
tasks_.push(std::move(task));
}
condition_.notify_one();
return ret;
}
~ThreadPool()
{
{
std::lock_guard<std::mutex> lck(mtx_);
exit_ = true;
}
condition_.notify_all();
for (auto &thr : workers_)
thr.join();
}
private:
std::mutex mtx_;
std::queue<std::unique_ptr<internal::TaskI>> tasks_;
std::condition_variable condition_;
bool exit_ = false;
std::array<std::thread, N> workers_;
};
#endif