libstdc++
std_thread.h
Go to the documentation of this file.
1// std::thread declarations -*- C++ -*-
2
3// Copyright (C) 2008-2022 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 bits/std_thread.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{thread}
28 */
29
30#ifndef _GLIBCXX_THREAD_H
31#define _GLIBCXX_THREAD_H 1
32
33#pragma GCC system_header
34
35#if __cplusplus >= 201103L
36#include <bits/c++config.h>
37
38#include <iosfwd> // std::basic_ostream
39#include <tuple> // std::tuple
40#include <bits/functional_hash.h> // std::hash
41#include <bits/invoke.h> // std::__invoke
42#include <bits/refwrap.h> // not required, but helpful to users
43#include <bits/unique_ptr.h> // std::unique_ptr
44
45#ifdef _GLIBCXX_HAS_GTHREADS
46# include <bits/gthr.h>
47#else
48# include <errno.h>
49# include <bits/functexcept.h>
50#endif
51
52namespace std _GLIBCXX_VISIBILITY(default)
53{
54_GLIBCXX_BEGIN_NAMESPACE_VERSION
55
56 /** @addtogroup threads
57 * @{
58 */
59
60 /** A std::thread represents a new thread of execution.
61 *
62 * The default constructor creates an object that does not own a thread.
63 * The `thread(F&&, Args&&...)` constructor invokes a callable in a new
64 * thread, and owns that new thread. A `std::thread` that owns a thread
65 * is *joinable*. Joining a thread waits for it to finish executing,
66 * which happens when the callable running in that thread returns.
67 *
68 * A `std::thread` cannot be copied, but can be moved. Moving a joinable
69 * object transfers ownership of its thread to another object.
70 *
71 * A joinable `std::thread` must be explicitly joined (or detached) before
72 * it is destroyed or assigned to. Attempting to destroy a joinable thread
73 * will terminate the whole process.
74 *
75 * @headerfile thread
76 * @since C++11
77 */
78 class thread
79 {
80 public:
81#ifdef _GLIBCXX_HAS_GTHREADS
82 using native_handle_type = __gthread_t;
83#else
84 using native_handle_type = int;
85#endif
86
87 /** A std::thread::id is a unique identifier for a thread.
88 *
89 * @headerfile thread
90 * @since C++11
91 */
92 class id
93 {
94 native_handle_type _M_thread;
95
96 public:
97 id() noexcept : _M_thread() { }
98
99 explicit
100 id(native_handle_type __id) : _M_thread(__id) { }
101
102 private:
103 friend class thread;
104 friend struct hash<id>;
105
106 friend bool
107 operator==(id __x, id __y) noexcept;
108
109#if __cpp_lib_three_way_comparison
110 friend strong_ordering
111 operator<=>(id __x, id __y) noexcept;
112#else
113 friend bool
114 operator<(id __x, id __y) noexcept;
115#endif
116
117 template<class _CharT, class _Traits>
120 };
121
122 private:
123 id _M_id;
124
125 // _GLIBCXX_RESOLVE_LIB_DEFECTS
126 // 2097. packaged_task constructors should be constrained
127 // 3039. Unnecessary decay in thread and packaged_task
128 template<typename _Tp>
129 using __not_same = __not_<is_same<__remove_cvref_t<_Tp>, thread>>;
130
131 public:
132 thread() noexcept = default;
133
134#ifdef _GLIBCXX_HAS_GTHREADS
135 template<typename _Callable, typename... _Args,
136 typename = _Require<__not_same<_Callable>>>
137 explicit
138 thread(_Callable&& __f, _Args&&... __args)
139 {
140 static_assert( __is_invocable<typename decay<_Callable>::type,
141 typename decay<_Args>::type...>::value,
142 "std::thread arguments must be invocable after conversion to rvalues"
143 );
144
145#ifdef GTHR_ACTIVE_PROXY
146 // Create a reference to pthread_create, not just the gthr weak symbol.
147 auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
148#else
149 auto __depend = nullptr;
150#endif
151 using _Wrapper = _Call_wrapper<_Callable, _Args...>;
152 // Create a call wrapper with DECAY_COPY(__f) as its target object
153 // and DECAY_COPY(__args)... as its bound argument entities.
154 _M_start_thread(_State_ptr(new _State_impl<_Wrapper>(
155 std::forward<_Callable>(__f), std::forward<_Args>(__args)...)),
156 __depend);
157 }
158#endif // _GLIBCXX_HAS_GTHREADS
159
160 ~thread()
161 {
162 if (joinable())
163 std::__terminate();
164 }
165
166 thread(const thread&) = delete;
167
168 thread(thread&& __t) noexcept
169 { swap(__t); }
170
171 thread& operator=(const thread&) = delete;
172
173 thread& operator=(thread&& __t) noexcept
174 {
175 if (joinable())
176 std::__terminate();
177 swap(__t);
178 return *this;
179 }
180
181 void
182 swap(thread& __t) noexcept
183 { std::swap(_M_id, __t._M_id); }
184
185 bool
186 joinable() const noexcept
187 { return !(_M_id == id()); }
188
189 void
190 join();
191
192 void
193 detach();
194
195 id
196 get_id() const noexcept
197 { return _M_id; }
198
199 /** @pre thread is joinable
200 */
201 native_handle_type
203 { return _M_id._M_thread; }
204
205 // Returns a value that hints at the number of hardware thread contexts.
206 static unsigned int
207 hardware_concurrency() noexcept;
208
209#ifdef _GLIBCXX_HAS_GTHREADS
210#ifndef _GLIBCXX_THREAD_IMPL
211 private:
212#endif
213 // Abstract base class for types that wrap arbitrary functors to be
214 // invoked in the new thread of execution.
215 struct _State
216 {
217 virtual ~_State();
218 virtual void _M_run() = 0;
219 };
220 using _State_ptr = unique_ptr<_State>;
221
222 private:
223 template<typename _Callable>
224 struct _State_impl : public _State
225 {
226 _Callable _M_func;
227
228 template<typename... _Args>
229 _State_impl(_Args&&... __args)
230 : _M_func(std::forward<_Args>(__args)...)
231 { }
232
233 void
234 _M_run() { _M_func(); }
235 };
236
237 void
238 _M_start_thread(_State_ptr, void (*)());
239
240#if _GLIBCXX_THREAD_ABI_COMPAT
241 public:
242 struct _Impl_base;
243 typedef shared_ptr<_Impl_base> __shared_base_type;
244 struct _Impl_base
245 {
246 __shared_base_type _M_this_ptr;
247 virtual ~_Impl_base() = default;
248 virtual void _M_run() = 0;
249 };
250
251 private:
252 void
253 _M_start_thread(__shared_base_type, void (*)());
254
255 void
256 _M_start_thread(__shared_base_type);
257#endif
258
259 private:
260 // A call wrapper that does INVOKE(forwarded tuple elements...)
261 template<typename _Tuple>
262 struct _Invoker
263 {
264 template<typename... _Args>
265 explicit
266 _Invoker(_Args&&... __args)
267 : _M_t(std::forward<_Args>(__args)...)
268 { }
269
270 _Tuple _M_t;
271
272 template<typename>
273 struct __result;
274 template<typename _Fn, typename... _Args>
275 struct __result<tuple<_Fn, _Args...>>
276 : __invoke_result<_Fn, _Args...>
277 { };
278
279 template<size_t... _Ind>
280 typename __result<_Tuple>::type
281 _M_invoke(_Index_tuple<_Ind...>)
282 { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
283
284 typename __result<_Tuple>::type
285 operator()()
286 {
287 using _Indices
288 = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
289 return _M_invoke(_Indices());
290 }
291 };
292
293 public:
294 /// @cond undocumented
295 template<typename... _Tp>
296 using _Call_wrapper = _Invoker<tuple<typename decay<_Tp>::type...>>;
297 /// @endcond
298#endif // _GLIBCXX_HAS_GTHREADS
299 };
300
301#ifndef _GLIBCXX_HAS_GTHREADS
302 inline void thread::join() { std::__throw_system_error(EINVAL); }
303 inline void thread::detach() { std::__throw_system_error(EINVAL); }
304 inline unsigned int thread::hardware_concurrency() noexcept { return 0; }
305#endif
306
307 /// @relates std::thread
308 inline void
309 swap(thread& __x, thread& __y) noexcept
310 { __x.swap(__y); }
311
312 /// @relates std::thread::id
313 inline bool
314 operator==(thread::id __x, thread::id __y) noexcept
315 {
316 // pthread_equal is undefined if either thread ID is not valid, so we
317 // can't safely use __gthread_equal on default-constructed values (nor
318 // the non-zero value returned by this_thread::get_id() for
319 // single-threaded programs using GNU libc). Assume EqualityComparable.
320 return __x._M_thread == __y._M_thread;
321 }
322
323 // N.B. other comparison operators are defined in <thread>
324
325 // DR 889.
326 /// std::hash specialization for thread::id.
327 template<>
328 struct hash<thread::id>
329 : public __hash_base<size_t, thread::id>
330 {
331 size_t
332 operator()(const thread::id& __id) const noexcept
333 { return std::_Hash_impl::hash(__id._M_thread); }
334 };
335
336 namespace this_thread
337 {
338 /// The unique identifier of the current thread.
339 inline thread::id
340 get_id() noexcept
341 {
342#ifndef _GLIBCXX_HAS_GTHREADS
343 return thread::id(1);
344#elif defined _GLIBCXX_NATIVE_THREAD_ID
345 return thread::id(_GLIBCXX_NATIVE_THREAD_ID);
346#else
347 return thread::id(__gthread_self());
348#endif
349 }
350
351 /// Allow the implementation to schedule a different thread.
352 inline void
353 yield() noexcept
354 {
355#if defined _GLIBCXX_HAS_GTHREADS && defined _GLIBCXX_USE_SCHED_YIELD
356 __gthread_yield();
357#endif
358 }
359
360 } // namespace this_thread
361
362 /// @}
363
364_GLIBCXX_END_NAMESPACE_VERSION
365} // namespace
366#endif // C++11
367
368#endif // _GLIBCXX_THREAD_H
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition: move.h:104
constexpr __invoke_result< _Callable, _Args... >::type __invoke(_Callable &&__fn, _Args &&... __args) noexcept(__is_nothrow_invocable< _Callable, _Args... >::value)
Invoke a callable object.
Definition: invoke.h:90
void swap(any &__x, any &__y) noexcept
Exchange the states of two any objects.
Definition: any:429
constexpr _Tp && forward(typename std::remove_reference< _Tp >::type &__t) noexcept
Forward an lvalue.
Definition: move.h:77
ISO C++ entities toplevel namespace is std.
std::basic_ostream< _CharT, _Traits > & operator<<(std::basic_ostream< _CharT, _Traits > &__os, const bitset< _Nb > &__x)
Global I/O operators for bitsets.
Definition: bitset:1685
void yield() noexcept
Allow the implementation to schedule a different thread.
Definition: std_thread.h:353
thread::id get_id() noexcept
The unique identifier of the current thread.
Definition: std_thread.h:340
Template class basic_ostream.
Definition: ostream:61
Primary class template hash.
native_handle_type native_handle()
Definition: std_thread.h:202
A move-only smart pointer that manages unique ownership of a resource.
Definition: unique_ptr.h:279