-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.h
More file actions
160 lines (140 loc) · 4.96 KB
/
Copy pathThreadPool.h
File metadata and controls
160 lines (140 loc) · 4.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
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
// MIT License
//
// Copyright (c) 2020 Dmitry Danilov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include <condition_variable>
#include <functional>
#include <future>
#include <mutex>
#include <queue>
#include <thread>
#include <utility>
#include <vector>
#include <type_traits>
#ifndef THREAD_POOL_NAMESPACE_NAME
#define THREAD_POOL_NAMESPACE_NAME thread_pool
#endif
#if _HAS_CXX17
template<class F, class... TN> using invoke_result_t = typename std::invoke_result<F, TN...>::type;
#else
template<class F, class... TN> using invoke_result_t = typename std::result_of<F(TN...)>::type;
#endif
namespace THREAD_POOL_NAMESPACE_NAME {
class ThreadPool {
private:
class TaskWrapper {
struct ImplBase {
virtual void call() = 0;
virtual ~ImplBase() = default;
};
std::unique_ptr<ImplBase> impl;
template <typename F>
struct ImplType : ImplBase {
F f;
ImplType(F&& f_) : f{ std::forward<F>(f_) } {}
void call() final { f(); }
};
public:
template <typename F>
TaskWrapper(F f) : impl{ std::make_unique<ImplType<F>>(std::move(f)) } {}
auto operator()() { impl->call(); }
};
class JoinThreads {
public:
explicit JoinThreads(std::vector<std::thread>& threads)
: _threads{ threads } {}
~JoinThreads() {
for (auto& t : _threads) {
t.join();
}
}
private:
std::vector<std::thread>& _threads;
};
public:
explicit ThreadPool(
size_t threadCount = std::thread::hardware_concurrency())
: _done{ false }, _joiner{ _threads } {
if (0u == threadCount) {
threadCount = 1u;
}
_threads.reserve(threadCount);
try {
for (size_t i = 0; i < threadCount; ++i) {
_threads.emplace_back(&ThreadPool::workerThread, this);
}
}
catch (...) {
_done = true;
_queue.cv.notify_all();
throw;
}
}
~ThreadPool() {
_done = true;
_queue.cv.notify_all();
}
size_t capacity() const { return _threads.size(); }
size_t queueSize() const {
std::unique_lock<std::mutex> l{ _queue.m };
return _queue.q.size();
}
template <typename FunctionT, typename... Args>
auto submit(FunctionT f, Args... args) {
using ResultT = typename std::invoke_result<FunctionT, Args...>::type;
std::packaged_task<ResultT()> task{ std::bind(f, args...) };
auto future = task.get_future();
{
std::lock_guard<std::mutex> l{ _queue.m };
_queue.q.push(std::move(task));
}
_queue.cv.notify_all();
return future;
}
ThreadPool(const ThreadPool&) = delete;
ThreadPool(ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
private:
void workerThread() {
while (!_done) {
std::unique_lock<std::mutex> l{ _queue.m };
_queue.cv.wait(l, [&] { return !_queue.q.empty() || _done; });
if (_done) {
break;
}
auto task = std::move(_queue.q.front());
_queue.q.pop();
l.unlock();
task();
}
}
struct TaskQueue {
std::queue<TaskWrapper> q;
std::mutex m;
std::condition_variable cv;
};
private:
std::atomic_bool _done;
mutable TaskQueue _queue;
std::vector<std::thread> _threads;
JoinThreads _joiner;
};
} // namespace THREAD_POOL_NAMESPACE_NAME