-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathAOThread_v2.h
More file actions
270 lines (208 loc) · 7.46 KB
/
AOThread_v2.h
File metadata and controls
270 lines (208 loc) · 7.46 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
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
259
260
261
262
263
264
265
266
267
268
269
270
/*
* AOThread.h
* C++17 based solution
* Created on: Aug 22, 2021
* Author: <a href="mailto:damirlj@yahoo.com">Damir Ljubic</a>
*/
#ifndef DS_AOT_AOTHREAD_H_
#define DS_AOT_AOTHREAD_H_
#include <thread>
#include <future>
#include <condition_variable>
#include <mutex>
#include <queue>
#include <memory>
#include <iostream>
#include <type_traits>
namespace utils::aot
{
template <typename Thread,
typename = std::enable_if_t<std::is_base_of_v<std::thread, Thread>>>
struct ThreadDeleter
{
void operator()(Thread * ptr) const
{
using namespace std;
if (ptr)
{
if (ptr->joinable()) ptr->join();
cout << "\nLeaving thread gracefully...\n";
delete ptr;
}
}
};
template <typename Thread>
using thread_with_deleter_t = std::unique_ptr<Thread, ThreadDeleter<Thread>>;
template <typename Thread, typename Func, typename...Args>
auto make_thread(Func&& func, Args&&...args)
{
return thread_with_deleter_t<Thread>(new (std::nothrow) Thread{std::forward<Func>(func)
, std::forward<Args>(args)...}
, ThreadDeleter<Thread>{}
);
}
/**
* Type Erasure
* For wrapping the only copy-constructible callable objects
* into movable object, since std::packaged_task is move-only
*/
class FunctionWrapper final
{
struct FunctionWrapperBase
{
virtual ~FunctionWrapperBase() = default;
virtual void call() = 0;
};
template <typename Func>
struct FunctionWrapperBaseImpl final : FunctionWrapperBase
{
FunctionWrapperBaseImpl(Func&& func):
m_func(std::move(func))
{}
~FunctionWrapperBaseImpl() override = default;
void call() override
{
m_func();
}
private:
Func m_func;
};
public:
template <typename Func>
FunctionWrapper(Func&& func):
m_pFunctionWrapper(std::make_unique<FunctionWrapperBaseImpl<Func>>(std::forward(func)))
{}
FunctionWrapper() = default;
~FunctionWrapper() = default;
// Move operations
FunctionWrapper(FunctionWrapper&& other) noexcept : m_pFunctionWrapper(std::exchange(other.m_pFunctionWrapper, nullptr))
{}
FunctionWrapper& operator=(FunctionWrapper&& other) noexcept
{
using namespace std;
FunctionWrapper tmp {std::move(other)};
swap(*this, tmp);
return *this;
}
// Copy-functions are forbidden
FunctionWrapper(const FunctionWrapper&) = delete;
FunctionWrapper& operator=(const FunctionWrapper&) = delete;
void operator ()()
{
m_pFunctionWrapper->call();
}
private:
std::unique_ptr<FunctionWrapperBase> m_pFunctionWrapper = nullptr;
};
/**
* AOT thread design pattern - heterogeneous version
* More flexible version which allows handling the heterogeneous jobs
* (of a different signature - return type)
*/
class AOThread final
{
public:
AOThread() = default;
~AOThread()
{
/*
* It's important to declare the mutex/conditional_variable first, then the job queue,
* and finally the thread itself to ensure the proper destruction in
* reversable order.
* Otherwise, we would need to force joining the thread explicitly, to prevent
* any undesirable effects (crashes)
*/
stop();
}
AOThread(const AOThread& ) = delete;
AOThread& operator = (const AOThread&) = delete;
template <typename Func>
auto enqueue(Func&& func)
{
using namespace std;
using result_t = invoke_result_t<Func>;
using task_t = packaged_task<result_t()>;
auto task = task_t{std::forward<Func>(func)};
auto result = task.get_future();
{
lock_guard<std::mutex> lock {m_lock};
// Call explicitly the task - so that the std::future is properly set
m_jobs.push(FunctionWrapper([task = std::move(task)]() mutable { task(); }));
}
m_condition.notify_one();
return result;
}
template <typename Func, typename...Args>
auto emplace_enqueue(Func&& func, Args&&...args)
{
using namespace std;
using result_t =invoke_result_t<Func&&, Args&&...>;
using task_t = packaged_task<result_t()>;
// Bind the data - additional arguments with the job: to satisfy the task (task_t) signature
auto task = task_t{std::bind(std::forward<Func>(func), std::forward<Args>(args)...)};
auto result = task.get_future();
{
lock_guard<mutex> lock {m_lock};
// Call explicitly the task - so that the std::future is properly set
m_jobs.push(FunctionWrapper{[task = std::move(task)]() mutable { task(); }});
}
m_condition.notify_one();
return result;
}
bool start()
{
try
{
m_pThread = make_thread<std::thread>(&AOThread::dequeue, this);
return true;
}
catch(...)
{
return false;
}
}
void stop()
{
if (!m_pThread) return;
{
std::lock_guard<std::mutex> lock {m_lock};
m_stopThread = true;
}
m_condition.notify_one();
m_pThread.reset(nullptr); // wait on thread to join
}
private:
void dequeue()
{
using namespace std;
for(;;)
{
FunctionWrapper job;
{
unique_lock<std::mutex> lock {m_lock};
m_condition.wait(lock, [this]{ return m_stopThread || !m_jobs.empty();});
if (m_stopThread) break;
job = move(m_jobs.front());
m_jobs.pop();
}
try
{
job();
}
catch (const bad_function_call& e)
{
cerr << e.what() << '\n';
//throw; // rethrow
}
}
}
private:
bool m_stopThread = false;
// @note: Order of declaration is important!
std::mutex m_lock;
std::condition_variable m_condition;
std::queue<FunctionWrapper> m_jobs;
thread_with_deleter_t<std::thread> m_pThread = nullptr;
};
}
#endif /* DS_AOT_AOTHREAD_H_ */