ad31fbc456f5d9aeb2913f3f00bff4945b4db451
[gcc.git] / libstdc++-v3 / include / std / thread
1 // <thread> -*- C++ -*-
2
3 // Copyright (C) 2008-2016 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
9 // any later version.
10
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
19
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
24
25 /** @file include/thread
26 * This is a Standard C++ Library header.
27 */
28
29 #ifndef _GLIBCXX_THREAD
30 #define _GLIBCXX_THREAD 1
31
32 #pragma GCC system_header
33
34 #if __cplusplus < 201103L
35 # include <bits/c++0x_warning.h>
36 #else
37
38 #include <chrono>
39 #include <functional>
40 #include <memory>
41 #include <cerrno>
42 #include <bits/functexcept.h>
43 #include <bits/functional_hash.h>
44 #include <bits/gthr.h>
45
46 #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
47
48 namespace std _GLIBCXX_VISIBILITY(default)
49 {
50 _GLIBCXX_BEGIN_NAMESPACE_VERSION
51
52 /**
53 * @defgroup threads Threads
54 * @ingroup concurrency
55 *
56 * Classes for thread support.
57 * @{
58 */
59
60 /// thread
61 class thread
62 {
63 public:
64 // Abstract base class for types that wrap arbitrary functors to be
65 // invoked in the new thread of execution.
66 struct _State
67 {
68 virtual ~_State();
69 virtual void _M_run() = 0;
70 };
71 using _State_ptr = unique_ptr<_State>;
72
73 typedef __gthread_t native_handle_type;
74
75 /// thread::id
76 class id
77 {
78 native_handle_type _M_thread;
79
80 public:
81 id() noexcept : _M_thread() { }
82
83 explicit
84 id(native_handle_type __id) : _M_thread(__id) { }
85
86 private:
87 friend class thread;
88 friend class hash<thread::id>;
89
90 friend bool
91 operator==(thread::id __x, thread::id __y) noexcept
92 {
93 // pthread_equal is undefined if either thread ID is not valid, so we
94 // can't safely use __gthread_equal on default-constructed values (nor
95 // the non-zero value returned by this_thread::get_id() for
96 // single-threaded programs using GNU libc). Assume EqualityComparable.
97 return __x._M_thread == __y._M_thread;
98 }
99
100 friend bool
101 operator<(thread::id __x, thread::id __y) noexcept
102 {
103 // Pthreads doesn't define any way to do this, so we just have to
104 // assume native_handle_type is LessThanComparable.
105 return __x._M_thread < __y._M_thread;
106 }
107
108 template<class _CharT, class _Traits>
109 friend basic_ostream<_CharT, _Traits>&
110 operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id);
111 };
112
113 private:
114 id _M_id;
115
116 public:
117 thread() noexcept = default;
118 // _GLIBCXX_RESOLVE_LIB_DEFECTS
119 // 2097. packaged_task constructors should be constrained
120 thread(thread&) = delete;
121 thread(const thread&) = delete;
122
123 thread(thread&& __t) noexcept
124 { swap(__t); }
125
126 template<typename _Callable, typename... _Args>
127 explicit
128 thread(_Callable&& __f, _Args&&... __args)
129 {
130 #ifdef GTHR_ACTIVE_PROXY
131 // Create a reference to pthread_create, not just the gthr weak symbol.
132 auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
133 #else
134 auto __depend = nullptr;
135 #endif
136 _M_start_thread(_S_make_state(
137 std::__bind_simple(std::forward<_Callable>(__f),
138 std::forward<_Args>(__args)...)),
139 __depend);
140 }
141
142 ~thread()
143 {
144 if (joinable())
145 std::terminate();
146 }
147
148 thread& operator=(const thread&) = delete;
149
150 thread& operator=(thread&& __t) noexcept
151 {
152 if (joinable())
153 std::terminate();
154 swap(__t);
155 return *this;
156 }
157
158 void
159 swap(thread& __t) noexcept
160 { std::swap(_M_id, __t._M_id); }
161
162 bool
163 joinable() const noexcept
164 { return !(_M_id == id()); }
165
166 void
167 join();
168
169 void
170 detach();
171
172 thread::id
173 get_id() const noexcept
174 { return _M_id; }
175
176 /** @pre thread is joinable
177 */
178 native_handle_type
179 native_handle()
180 { return _M_id._M_thread; }
181
182 // Returns a value that hints at the number of hardware thread contexts.
183 static unsigned int
184 hardware_concurrency() noexcept;
185
186 private:
187 template<typename _Callable>
188 struct _State_impl : public _State
189 {
190 _Callable _M_func;
191
192 _State_impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f))
193 { }
194
195 void
196 _M_run() { _M_func(); }
197 };
198
199 void
200 _M_start_thread(_State_ptr, void (*)());
201
202 template<typename _Callable>
203 static _State_ptr
204 _S_make_state(_Callable&& __f)
205 {
206 using _Impl = _State_impl<_Callable>;
207 return _State_ptr{new _Impl{std::forward<_Callable>(__f)}};
208 }
209 #if _GLIBCXX_THREAD_ABI_COMPAT
210 public:
211 struct _Impl_base;
212 typedef shared_ptr<_Impl_base> __shared_base_type;
213 struct _Impl_base
214 {
215 __shared_base_type _M_this_ptr;
216 virtual ~_Impl_base() = default;
217 virtual void _M_run() = 0;
218 };
219
220 private:
221 void
222 _M_start_thread(__shared_base_type, void (*)());
223
224 void
225 _M_start_thread(__shared_base_type);
226 #endif
227 };
228
229 inline void
230 swap(thread& __x, thread& __y) noexcept
231 { __x.swap(__y); }
232
233 inline bool
234 operator!=(thread::id __x, thread::id __y) noexcept
235 { return !(__x == __y); }
236
237 inline bool
238 operator<=(thread::id __x, thread::id __y) noexcept
239 { return !(__y < __x); }
240
241 inline bool
242 operator>(thread::id __x, thread::id __y) noexcept
243 { return __y < __x; }
244
245 inline bool
246 operator>=(thread::id __x, thread::id __y) noexcept
247 { return !(__x < __y); }
248
249 // DR 889.
250 /// std::hash specialization for thread::id.
251 template<>
252 struct hash<thread::id>
253 : public __hash_base<size_t, thread::id>
254 {
255 size_t
256 operator()(const thread::id& __id) const noexcept
257 { return std::_Hash_impl::hash(__id._M_thread); }
258 };
259
260 template<class _CharT, class _Traits>
261 inline basic_ostream<_CharT, _Traits>&
262 operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
263 {
264 if (__id == thread::id())
265 return __out << "thread::id of a non-executing thread";
266 else
267 return __out << __id._M_thread;
268 }
269
270 _GLIBCXX_END_NAMESPACE_VERSION
271
272 /** @namespace std::this_thread
273 * @brief ISO C++ 2011 entities sub-namespace for thread.
274 * 30.3.2 Namespace this_thread.
275 */
276 namespace this_thread
277 {
278 _GLIBCXX_BEGIN_NAMESPACE_VERSION
279
280 /// get_id
281 inline thread::id
282 get_id() noexcept
283 {
284 #ifdef __GLIBC__
285 // For the GNU C library pthread_self() is usable without linking to
286 // libpthread.so but returns 0, so we cannot use it in single-threaded
287 // programs, because this_thread::get_id() != thread::id{} must be true.
288 // We know that pthread_t is an integral type in the GNU C library.
289 if (!__gthread_active_p())
290 return thread::id(1);
291 #endif
292 return thread::id(__gthread_self());
293 }
294
295 /// yield
296 inline void
297 yield() noexcept
298 {
299 #ifdef _GLIBCXX_USE_SCHED_YIELD
300 __gthread_yield();
301 #endif
302 }
303
304 void
305 __sleep_for(chrono::seconds, chrono::nanoseconds);
306
307 /// sleep_for
308 template<typename _Rep, typename _Period>
309 inline void
310 sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
311 {
312 if (__rtime <= __rtime.zero())
313 return;
314 auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
315 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
316 #ifdef _GLIBCXX_USE_NANOSLEEP
317 __gthread_time_t __ts =
318 {
319 static_cast<std::time_t>(__s.count()),
320 static_cast<long>(__ns.count())
321 };
322 while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
323 { }
324 #else
325 __sleep_for(__s, __ns);
326 #endif
327 }
328
329 /// sleep_until
330 template<typename _Clock, typename _Duration>
331 inline void
332 sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
333 {
334 auto __now = _Clock::now();
335 if (_Clock::is_steady)
336 {
337 if (__now < __atime)
338 sleep_for(__atime - __now);
339 return;
340 }
341 while (__now < __atime)
342 {
343 sleep_for(__atime - __now);
344 __now = _Clock::now();
345 }
346 }
347
348 _GLIBCXX_END_NAMESPACE_VERSION
349 }
350
351 // @} group threads
352
353 } // namespace
354
355 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
356
357 #endif // C++11
358
359 #endif // _GLIBCXX_THREAD