1 // <thread> -*- C++ -*-
3 // Copyright (C) 2008-2017 Free Software Foundation, Inc.
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)
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.
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.
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/>.
25 /** @file include/thread
26 * This is a Standard C++ Library header.
29 #ifndef _GLIBCXX_THREAD
30 #define _GLIBCXX_THREAD 1
32 #pragma GCC system_header
34 #if __cplusplus < 201103L
35 # include <bits/c++0x_warning.h>
42 #include <bits/functexcept.h>
43 #include <bits/functional_hash.h>
44 #include <bits/invoke.h>
45 #include <bits/gthr.h>
47 #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
49 namespace std _GLIBCXX_VISIBILITY(default)
51 _GLIBCXX_BEGIN_NAMESPACE_VERSION
54 * @defgroup threads Threads
55 * @ingroup concurrency
57 * Classes for thread support.
65 // Abstract base class for types that wrap arbitrary functors to be
66 // invoked in the new thread of execution.
70 virtual void _M_run() = 0;
72 using _State_ptr = unique_ptr<_State>;
74 typedef __gthread_t native_handle_type;
79 native_handle_type _M_thread;
82 id() noexcept : _M_thread() { }
85 id(native_handle_type __id) : _M_thread(__id) { }
89 friend class hash<thread::id>;
92 operator==(thread::id __x, thread::id __y) noexcept;
95 operator<(thread::id __x, thread::id __y) noexcept;
97 template<class _CharT, class _Traits>
98 friend basic_ostream<_CharT, _Traits>&
99 operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id);
106 thread() noexcept = default;
107 // _GLIBCXX_RESOLVE_LIB_DEFECTS
108 // 2097. packaged_task constructors should be constrained
109 thread(thread&) = delete;
110 thread(const thread&) = delete;
111 thread(const thread&&) = delete;
113 thread(thread&& __t) noexcept
116 template<typename _Callable, typename... _Args>
118 thread(_Callable&& __f, _Args&&... __args)
120 #ifdef GTHR_ACTIVE_PROXY
121 // Create a reference to pthread_create, not just the gthr weak symbol.
122 auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
124 auto __depend = nullptr;
126 _M_start_thread(_S_make_state(
127 __make_invoker(std::forward<_Callable>(__f),
128 std::forward<_Args>(__args)...)),
138 thread& operator=(const thread&) = delete;
140 thread& operator=(thread&& __t) noexcept
149 swap(thread& __t) noexcept
150 { std::swap(_M_id, __t._M_id); }
153 joinable() const noexcept
154 { return !(_M_id == id()); }
163 get_id() const noexcept
166 /** @pre thread is joinable
170 { return _M_id._M_thread; }
172 // Returns a value that hints at the number of hardware thread contexts.
174 hardware_concurrency() noexcept;
177 template<typename _Callable>
178 struct _State_impl : public _State
182 _State_impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f))
186 _M_run() { _M_func(); }
190 _M_start_thread(_State_ptr, void (*)());
192 template<typename _Callable>
194 _S_make_state(_Callable&& __f)
196 using _Impl = _State_impl<_Callable>;
197 return _State_ptr{new _Impl{std::forward<_Callable>(__f)}};
199 #if _GLIBCXX_THREAD_ABI_COMPAT
202 typedef shared_ptr<_Impl_base> __shared_base_type;
205 __shared_base_type _M_this_ptr;
206 virtual ~_Impl_base() = default;
207 virtual void _M_run() = 0;
212 _M_start_thread(__shared_base_type, void (*)());
215 _M_start_thread(__shared_base_type);
219 // A call wrapper that does INVOKE(forwarded tuple elements...)
220 template<typename _Tuple>
225 template<size_t _Index>
226 static __tuple_element_t<_Index, _Tuple>&&
229 template<size_t... _Ind>
231 _M_invoke(_Index_tuple<_Ind...>)
232 noexcept(noexcept(std::__invoke(_S_declval<_Ind>()...)))
233 -> decltype(std::__invoke(_S_declval<_Ind>()...))
234 { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
237 = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
241 noexcept(noexcept(std::declval<_Invoker&>()._M_invoke(_Indices())))
242 -> decltype(std::declval<_Invoker&>()._M_invoke(_Indices()))
243 { return _M_invoke(_Indices()); }
246 template<typename... _Tp>
247 using __decayed_tuple = tuple<typename std::decay<_Tp>::type...>;
250 // Returns a call wrapper that stores
251 // tuple{DECAY_COPY(__callable), DECAY_COPY(__args)...}.
252 template<typename _Callable, typename... _Args>
253 static _Invoker<__decayed_tuple<_Callable, _Args...>>
254 __make_invoker(_Callable&& __callable, _Args&&... __args)
256 return { __decayed_tuple<_Callable, _Args...>{
257 std::forward<_Callable>(__callable), std::forward<_Args>(__args)...
263 swap(thread& __x, thread& __y) noexcept
267 operator==(thread::id __x, thread::id __y) noexcept
269 // pthread_equal is undefined if either thread ID is not valid, so we
270 // can't safely use __gthread_equal on default-constructed values (nor
271 // the non-zero value returned by this_thread::get_id() for
272 // single-threaded programs using GNU libc). Assume EqualityComparable.
273 return __x._M_thread == __y._M_thread;
277 operator!=(thread::id __x, thread::id __y) noexcept
278 { return !(__x == __y); }
281 operator<(thread::id __x, thread::id __y) noexcept
283 // Pthreads doesn't define any way to do this, so we just have to
284 // assume native_handle_type is LessThanComparable.
285 return __x._M_thread < __y._M_thread;
289 operator<=(thread::id __x, thread::id __y) noexcept
290 { return !(__y < __x); }
293 operator>(thread::id __x, thread::id __y) noexcept
294 { return __y < __x; }
297 operator>=(thread::id __x, thread::id __y) noexcept
298 { return !(__x < __y); }
301 /// std::hash specialization for thread::id.
303 struct hash<thread::id>
304 : public __hash_base<size_t, thread::id>
307 operator()(const thread::id& __id) const noexcept
308 { return std::_Hash_impl::hash(__id._M_thread); }
311 template<class _CharT, class _Traits>
312 inline basic_ostream<_CharT, _Traits>&
313 operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
315 if (__id == thread::id())
316 return __out << "thread::id of a non-executing thread";
318 return __out << __id._M_thread;
321 _GLIBCXX_END_NAMESPACE_VERSION
323 /** @namespace std::this_thread
324 * @brief ISO C++ 2011 entities sub-namespace for thread.
325 * 30.3.2 Namespace this_thread.
327 namespace this_thread
329 _GLIBCXX_BEGIN_NAMESPACE_VERSION
336 // For the GNU C library pthread_self() is usable without linking to
337 // libpthread.so but returns 0, so we cannot use it in single-threaded
338 // programs, because this_thread::get_id() != thread::id{} must be true.
339 // We know that pthread_t is an integral type in the GNU C library.
340 if (!__gthread_active_p())
341 return thread::id(1);
343 return thread::id(__gthread_self());
350 #ifdef _GLIBCXX_USE_SCHED_YIELD
356 __sleep_for(chrono::seconds, chrono::nanoseconds);
359 template<typename _Rep, typename _Period>
361 sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
363 if (__rtime <= __rtime.zero())
365 auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
366 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
367 #ifdef _GLIBCXX_USE_NANOSLEEP
368 __gthread_time_t __ts =
370 static_cast<std::time_t>(__s.count()),
371 static_cast<long>(__ns.count())
373 while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
376 __sleep_for(__s, __ns);
381 template<typename _Clock, typename _Duration>
383 sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
385 auto __now = _Clock::now();
386 if (_Clock::is_steady)
389 sleep_for(__atime - __now);
392 while (__now < __atime)
394 sleep_for(__atime - __now);
395 __now = _Clock::now();
399 _GLIBCXX_END_NAMESPACE_VERSION
406 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
410 #endif // _GLIBCXX_THREAD