thread.hpp
9.92 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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/*
* Copyright (C) 2015 Hamburg University of Applied Sciences (HAW)
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
*/
/**
* @ingroup cpp11-compat
* @{
*
* @file
* @brief C++11 thread drop in replacement
* @see <a href="http://en.cppreference.com/w/cpp/thread/thread">
* std::thread, std::this_thread
* </a>
*
* @author Raphael Hiesgen <raphael.hiesgen (at) haw-hamburg.de>
*
* @}
*/
#ifndef RIOT_THREAD_HPP
#define RIOT_THREAD_HPP
#include "time.h"
#include "thread.h"
#include <array>
#include <tuple>
#include <atomic>
#include <memory>
#include <utility>
#include <exception>
#include <stdexcept>
#include <functional>
#include <type_traits>
#include "riot/mutex.hpp"
#include "riot/chrono.hpp"
#include "riot/condition_variable.hpp"
#include "riot/detail/thread_util.hpp"
namespace riot {
namespace {
/**
* @brief Identify uninitialized threads.
*/
constexpr kernel_pid_t thread_uninitialized = -1;
/**
* @brief The stack size for new threads.
*/
constexpr size_t stack_size = THREAD_STACKSIZE_MAIN;
}
/**
* @brief Holds context data for the thread.
*/
struct thread_data {
thread_data() : ref_count{2}, joining_thread{thread_uninitialized} {
// nop
}
/** @cond INTERNAL */
std::atomic<unsigned> ref_count;
kernel_pid_t joining_thread;
std::array<char, stack_size> stack;
/** @endcond */
};
/**
* @brief This deleter prevents our thread data from being destroyed if the
* thread object is destroyed before the thread had a chance to run.
*/
struct thread_data_deleter {
/**
* @brief Called by the deleter of a thread object to manage the lifetime of
* the thread internal management data.
*/
void operator()(thread_data* ptr) {
if (--ptr->ref_count == 0) {
delete ptr;
}
}
};
/**
* @brief implementation of thread::id
* @see <a href="http://en.cppreference.com/w/cpp/thread/thread/id">
* thread::id
* </a>
*/
class thread_id {
template <class T, class Traits>
friend std::basic_ostream<T, Traits>& operator<<(std::basic_ostream
<T, Traits>& out,
thread_id id);
friend class thread;
public:
/**
* @brief Creates a uninitialized thread id.
*/
inline thread_id() noexcept : m_handle{thread_uninitialized} {}
/**
* @brief Create a thread id from a native handle.
*/
explicit inline thread_id(kernel_pid_t handle) : m_handle{handle} {}
/**
* @brief Comparison operator for thread ids.
*/
inline bool operator==(thread_id other) noexcept {
return m_handle == other.m_handle;
}
/**
* @brief Comparison operator for thread ids.
*/
inline bool operator!=(thread_id other) noexcept {
return !(m_handle == other.m_handle);
}
/**
* @brief Comparison operator for thread ids.
*/
inline bool operator<(thread_id other) noexcept {
return m_handle < other.m_handle;
}
/**
* @brief Comparison operator for thread ids.
*/
inline bool operator<=(thread_id other) noexcept {
return !(m_handle > other.m_handle);
}
/**
* @brief Comparison operator for thread ids.
*/
inline bool operator>(thread_id other) noexcept {
return m_handle > other.m_handle;
}
/**
* @brief Comparison operator for thread ids.
*/
inline bool operator>=(thread_id other) noexcept {
return !(m_handle < other.m_handle);
}
private:
kernel_pid_t m_handle;
};
/**
* @brief Enable printing of thread ids using output streams.
*/
template <class T, class Traits>
inline std::basic_ostream<T, Traits>& operator<<(std::basic_ostream
<T, Traits>& out,
thread_id id) {
return out << id.m_handle;
}
namespace this_thread {
/**
* @brief Access the id of the currently running thread.
*/
inline thread_id get_id() noexcept { return thread_id{thread_getpid()}; }
/**
* @brief Yield the currently running thread.
*/
inline void yield() noexcept { thread_yield(); }
/**
* @brief Puts the current thread to sleep.
* @param[in] ns Duration to sleep in nanoseconds.
*/
void sleep_for(const std::chrono::nanoseconds& ns);
/**
* @brief Puts the current thread to sleep.
* @param[in] sleep_duration The duration to sleep.
*/
template <class Rep, class Period>
void sleep_for(const std::chrono::duration<Rep, Period>& sleep_duration) {
using namespace std::chrono;
if (sleep_duration > std::chrono::duration<Rep, Period>::zero()) {
constexpr std::chrono::duration<long double> max = nanoseconds::max();
nanoseconds ns;
if (sleep_duration < max) {
ns = duration_cast<nanoseconds>(sleep_duration);
if (ns < sleep_duration) {
++ns;
}
} else {
ns = nanoseconds::max();
}
sleep_for(ns);
}
}
/**
* @brief Puts the current thread to sleep.
* @param[in] sleep_time A point in time that specifies when the thread
* should wake up.
*/
inline void sleep_until(const riot::time_point& sleep_time) {
mutex mtx;
condition_variable cv;
unique_lock<mutex> lk(mtx);
while (riot::now() < sleep_time) {
cv.wait_until(lk, sleep_time);
}
}
} // namespace this_thread
/**
* @brief C++11 compliant implementation of thread, however uses the time
* point from out chrono header instead of the specified one
* @see <a href="http://en.cppreference.com/w/cpp/thread/thread">
* std::thread
* </a>
*/
class thread {
public:
/**
* @brief The id is of type `thread_id`-
*/
using id = thread_id;
/**
* @brief The native handle type is the `kernel_pid_t` of RIOT.
*/
using native_handle_type = kernel_pid_t;
/**
* @brief Per default, an uninitialized thread is created.
*/
inline thread() noexcept : m_handle{thread_uninitialized} {}
/**
* @brief Create a thread from a functor and arguments for it.
* @param[in] f Functor to run as a thread.
* @param[in] args Arguments passed to the functor.
*/
template <class F, class... Args>
explicit thread(F&& f, Args&&... args);
/**
* @brief Disallow copy constructor.
*/
thread(const thread&) = delete;
/**
* @brief Move constructor.
*/
inline thread(thread&& t) noexcept : m_handle{t.m_handle} {
t.m_handle = thread_uninitialized;
std::swap(m_data, t.m_data);
}
~thread();
/**
* @brief Disallow copy assignment operator.
*/
thread& operator=(const thread&) = delete;
/**
* @brief Move assignment operator.
*/
thread& operator=(thread&&) noexcept;
/**
* @brief Swap threads.
* @param[inout] t Thread to swap data with.
*/
void swap(thread& t) noexcept {
std::swap(m_data, t.m_data);
std::swap(m_handle, t.m_handle);
}
/**
* @brief Query if the thread is joinable.
* @return `true` if the thread is joinable, `false` otherwise.
*/
inline bool joinable() const noexcept {
return m_handle != thread_uninitialized;
}
/**
* @brief Block until the thread finishes. Leads to an error if the thread is
* not joinable or a thread joins itself.
*/
void join();
/**
* @brief Detaches a thread from its handle and allows it to execute
* independently. The thread cleans up its resources when it
* finishes.
*/
void detach();
/**
* @brief Returns the id of a thread.
*/
inline id get_id() const noexcept { return thread_id{m_handle}; }
/**
* @brief Returns the native handle to a thread.
*/
inline native_handle_type native_handle() noexcept { return m_handle; }
/**
* @brief Returns the number of concurrent threads supported by the
* underlying hardware. Since there is no RIOT API to query this
* information, the function always returns 1;
*/
static unsigned hardware_concurrency() noexcept;
private:
kernel_pid_t m_handle;
std::unique_ptr<thread_data, thread_data_deleter> m_data;
};
/**
* @brief Swaps two threads.
* @param[inout] lhs Reference to one thread.
* @param[inout] rhs Reference to the other thread.
*/
void swap(thread& lhs, thread& rhs) noexcept;
/** @cond INTERNAL */
template <class Tuple>
void* thread_proxy(void* vp) {
{ // without this scope, the objects here are not cleaned up corrctly
std::unique_ptr<Tuple> p(static_cast<Tuple*>(vp));
auto tmp = std::get<0>(*p);
std::unique_ptr<thread_data, thread_data_deleter> data{tmp};
// create indices for the arguments, 0 is thread_data and 1 is the function
auto indices = detail::get_indices<std::tuple_size<Tuple>::value, 2>();
try {
detail::apply_args(std::get<1>(*p), indices, *p);
}
catch (...) {
// nop
}
if (data->joining_thread != thread_uninitialized) {
thread_wakeup(data->joining_thread);
}
}
// some riot cleanup code
sched_task_exit();
return nullptr;
}
/** @endcond */
template <class F, class... Args>
thread::thread(F&& f, Args&&... args)
: m_data{new thread_data} {
using namespace std;
using func_and_args = tuple
<thread_data*, typename decay<F>::type, typename decay<Args>::type...>;
unique_ptr<func_and_args> p(
new func_and_args(m_data.get(), forward<F>(f), forward<Args>(args)...));
m_handle = thread_create(
m_data->stack.data(), stack_size, THREAD_PRIORITY_MAIN - 1, 0,
&thread_proxy<func_and_args>, p.get(), "riot_cpp_thread");
if (m_handle >= 0) {
p.release();
} else {
throw std::system_error(
std::make_error_code(std::errc::resource_unavailable_try_again),
"Failed to create thread.");
}
}
inline thread& thread::operator=(thread&& other) noexcept {
if (m_handle != thread_uninitialized) {
std::terminate();
}
m_handle = other.m_handle;
other.m_handle = thread_uninitialized;
std::swap(m_data, other.m_data);
return *this;
}
inline void swap(thread& lhs, thread& rhs) noexcept { lhs.swap(rhs); }
} // namespace riot
#endif // RIOT_THREAD_HPP