]> git.ipfire.org Git - thirdparty/gcc.git/blob - libstdc++-v3/include/std/thread
libstdc++: Remove redundant copying of std::async arguments [PR 69724]
[thirdparty/gcc.git] / libstdc++-v3 / include / std / thread
1 // <thread> -*- C++ -*-
2
3 // Copyright (C) 2008-2020 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> // std::chrono::*
39
40 #ifdef _GLIBCXX_USE_NANOSLEEP
41 # include <cerrno> // errno, EINTR
42 # include <time.h> // nanosleep
43 #endif
44
45 #if defined(_GLIBCXX_HAS_GTHREADS)
46 #include <bits/gthr.h>
47
48 #include <memory> // std::unique_ptr
49 #include <tuple> // std::tuple
50
51 #if __cplusplus > 201703L
52 # include <compare> // std::strong_ordering
53 # include <stop_token> // std::stop_source, std::stop_token, std::nostopstate
54 #endif
55
56 #include <bits/functional_hash.h> // std::hash
57 #include <bits/invoke.h> // std::__invoke
58
59 #endif // _GLIBCXX_HAS_GTHREADS
60
61 namespace std _GLIBCXX_VISIBILITY(default)
62 {
63 _GLIBCXX_BEGIN_NAMESPACE_VERSION
64
65 /**
66 * @defgroup threads Threads
67 * @ingroup concurrency
68 *
69 * Classes for thread support.
70 * @{
71 */
72
73 #if defined(_GLIBCXX_HAS_GTHREADS)
74 /// thread
75 class thread
76 {
77 public:
78 // Abstract base class for types that wrap arbitrary functors to be
79 // invoked in the new thread of execution.
80 struct _State
81 {
82 virtual ~_State();
83 virtual void _M_run() = 0;
84 };
85 using _State_ptr = unique_ptr<_State>;
86
87 typedef __gthread_t native_handle_type;
88
89 /// thread::id
90 class id
91 {
92 native_handle_type _M_thread;
93
94 public:
95 id() noexcept : _M_thread() { }
96
97 explicit
98 id(native_handle_type __id) : _M_thread(__id) { }
99
100 private:
101 friend class thread;
102 friend struct hash<id>;
103
104 friend bool
105 operator==(id __x, id __y) noexcept;
106
107 #if __cpp_lib_three_way_comparison
108 friend strong_ordering
109 operator<=>(id __x, id __y) noexcept;
110 #else
111 friend bool
112 operator<(id __x, id __y) noexcept;
113 #endif
114
115 template<class _CharT, class _Traits>
116 friend basic_ostream<_CharT, _Traits>&
117 operator<<(basic_ostream<_CharT, _Traits>& __out, id __id);
118 };
119
120 private:
121 id _M_id;
122
123 // _GLIBCXX_RESOLVE_LIB_DEFECTS
124 // 2097. packaged_task constructors should be constrained
125 // 3039. Unnecessary decay in thread and packaged_task
126 template<typename _Tp>
127 using __not_same = __not_<is_same<__remove_cvref_t<_Tp>, thread>>;
128
129 public:
130 thread() noexcept = default;
131
132 template<typename _Callable, typename... _Args,
133 typename = _Require<__not_same<_Callable>>>
134 explicit
135 thread(_Callable&& __f, _Args&&... __args)
136 {
137 static_assert( __is_invocable<typename decay<_Callable>::type,
138 typename decay<_Args>::type...>::value,
139 "std::thread arguments must be invocable after conversion to rvalues"
140 );
141
142 #ifdef GTHR_ACTIVE_PROXY
143 // Create a reference to pthread_create, not just the gthr weak symbol.
144 auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
145 #else
146 auto __depend = nullptr;
147 #endif
148 using _Wrapper = _Call_wrapper<_Callable, _Args...>;
149 // Create a call wrapper with DECAY_COPY(__f) as its target object
150 // and DECAY_COPY(__args)... as its bound argument entities.
151 _M_start_thread(_State_ptr(new _State_impl<_Wrapper>(
152 std::forward<_Callable>(__f), std::forward<_Args>(__args)...)),
153 __depend);
154 }
155
156 ~thread()
157 {
158 if (joinable())
159 std::terminate();
160 }
161
162 thread(const thread&) = delete;
163
164 thread(thread&& __t) noexcept
165 { swap(__t); }
166
167 thread& operator=(const thread&) = delete;
168
169 thread& operator=(thread&& __t) noexcept
170 {
171 if (joinable())
172 std::terminate();
173 swap(__t);
174 return *this;
175 }
176
177 void
178 swap(thread& __t) noexcept
179 { std::swap(_M_id, __t._M_id); }
180
181 bool
182 joinable() const noexcept
183 { return !(_M_id == id()); }
184
185 void
186 join();
187
188 void
189 detach();
190
191 id
192 get_id() const noexcept
193 { return _M_id; }
194
195 /** @pre thread is joinable
196 */
197 native_handle_type
198 native_handle()
199 { return _M_id._M_thread; }
200
201 // Returns a value that hints at the number of hardware thread contexts.
202 static unsigned int
203 hardware_concurrency() noexcept;
204
205 private:
206 template<typename _Callable>
207 struct _State_impl : public _State
208 {
209 _Callable _M_func;
210
211 template<typename... _Args>
212 _State_impl(_Args&&... __args)
213 : _M_func{{std::forward<_Args>(__args)...}}
214 { }
215
216 void
217 _M_run() { _M_func(); }
218 };
219
220 void
221 _M_start_thread(_State_ptr, void (*)());
222
223 #if _GLIBCXX_THREAD_ABI_COMPAT
224 public:
225 struct _Impl_base;
226 typedef shared_ptr<_Impl_base> __shared_base_type;
227 struct _Impl_base
228 {
229 __shared_base_type _M_this_ptr;
230 virtual ~_Impl_base() = default;
231 virtual void _M_run() = 0;
232 };
233
234 private:
235 void
236 _M_start_thread(__shared_base_type, void (*)());
237
238 void
239 _M_start_thread(__shared_base_type);
240 #endif
241
242 private:
243 // A call wrapper that does INVOKE(forwarded tuple elements...)
244 template<typename _Tuple>
245 struct _Invoker
246 {
247 _Tuple _M_t;
248
249 template<typename>
250 struct __result;
251 template<typename _Fn, typename... _Args>
252 struct __result<tuple<_Fn, _Args...>>
253 : __invoke_result<_Fn, _Args...>
254 { };
255
256 template<size_t... _Ind>
257 typename __result<_Tuple>::type
258 _M_invoke(_Index_tuple<_Ind...>)
259 { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
260
261 typename __result<_Tuple>::type
262 operator()()
263 {
264 using _Indices
265 = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
266 return _M_invoke(_Indices());
267 }
268 };
269
270 public:
271 template<typename... _Tp>
272 using _Call_wrapper = _Invoker<tuple<typename decay<_Tp>::type...>>;
273 };
274
275 inline void
276 swap(thread& __x, thread& __y) noexcept
277 { __x.swap(__y); }
278
279 inline bool
280 operator==(thread::id __x, thread::id __y) noexcept
281 {
282 // pthread_equal is undefined if either thread ID is not valid, so we
283 // can't safely use __gthread_equal on default-constructed values (nor
284 // the non-zero value returned by this_thread::get_id() for
285 // single-threaded programs using GNU libc). Assume EqualityComparable.
286 return __x._M_thread == __y._M_thread;
287 }
288
289 #if __cpp_lib_three_way_comparison
290 inline strong_ordering
291 operator<=>(thread::id __x, thread::id __y) noexcept
292 { return __x._M_thread <=> __y._M_thread; }
293 #else
294 inline bool
295 operator!=(thread::id __x, thread::id __y) noexcept
296 { return !(__x == __y); }
297
298 inline bool
299 operator<(thread::id __x, thread::id __y) noexcept
300 {
301 // Pthreads doesn't define any way to do this, so we just have to
302 // assume native_handle_type is LessThanComparable.
303 return __x._M_thread < __y._M_thread;
304 }
305
306 inline bool
307 operator<=(thread::id __x, thread::id __y) noexcept
308 { return !(__y < __x); }
309
310 inline bool
311 operator>(thread::id __x, thread::id __y) noexcept
312 { return __y < __x; }
313
314 inline bool
315 operator>=(thread::id __x, thread::id __y) noexcept
316 { return !(__x < __y); }
317 #endif // __cpp_lib_three_way_comparison
318
319 // DR 889.
320 /// std::hash specialization for thread::id.
321 template<>
322 struct hash<thread::id>
323 : public __hash_base<size_t, thread::id>
324 {
325 size_t
326 operator()(const thread::id& __id) const noexcept
327 { return std::_Hash_impl::hash(__id._M_thread); }
328 };
329
330 template<class _CharT, class _Traits>
331 inline basic_ostream<_CharT, _Traits>&
332 operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
333 {
334 if (__id == thread::id())
335 return __out << "thread::id of a non-executing thread";
336 else
337 return __out << __id._M_thread;
338 }
339 #endif // _GLIBCXX_HAS_GTHREADS
340
341 /** @namespace std::this_thread
342 * @brief ISO C++ 2011 namespace for interacting with the current thread
343 *
344 * C++11 30.3.2 [thread.thread.this] Namespace this_thread.
345 */
346 namespace this_thread
347 {
348 #if defined _GLIBCXX_HAS_GTHREADS
349 /// get_id
350 inline thread::id
351 get_id() noexcept
352 {
353 #ifdef __GLIBC__
354 // For the GNU C library pthread_self() is usable without linking to
355 // libpthread.so but returns 0, so we cannot use it in single-threaded
356 // programs, because this_thread::get_id() != thread::id{} must be true.
357 // We know that pthread_t is an integral type in the GNU C library.
358 if (!__gthread_active_p())
359 return thread::id(1);
360 #endif
361 return thread::id(__gthread_self());
362 }
363 #endif // _GLIBCXX_HAS_GTHREADS
364
365 /// yield
366 inline void
367 yield() noexcept
368 {
369 #if defined _GLIBCXX_HAS_GTHREADS && defined _GLIBCXX_USE_SCHED_YIELD
370 __gthread_yield();
371 #endif
372 }
373
374 void
375 __sleep_for(chrono::seconds, chrono::nanoseconds);
376
377 /// sleep_for
378 template<typename _Rep, typename _Period>
379 inline void
380 sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
381 {
382 if (__rtime <= __rtime.zero())
383 return;
384 auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
385 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
386 #ifdef _GLIBCXX_USE_NANOSLEEP
387 struct ::timespec __ts =
388 {
389 static_cast<std::time_t>(__s.count()),
390 static_cast<long>(__ns.count())
391 };
392 while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
393 { }
394 #else
395 __sleep_for(__s, __ns);
396 #endif
397 }
398
399 /// sleep_until
400 template<typename _Clock, typename _Duration>
401 inline void
402 sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
403 {
404 #if __cplusplus > 201703L
405 static_assert(chrono::is_clock_v<_Clock>);
406 #endif
407 auto __now = _Clock::now();
408 if (_Clock::is_steady)
409 {
410 if (__now < __atime)
411 sleep_for(__atime - __now);
412 return;
413 }
414 while (__now < __atime)
415 {
416 sleep_for(__atime - __now);
417 __now = _Clock::now();
418 }
419 }
420 }
421
422 #ifdef __cpp_lib_jthread
423
424 class jthread
425 {
426 public:
427 using id = thread::id;
428 using native_handle_type = thread::native_handle_type;
429
430 jthread() noexcept
431 : _M_stop_source{nostopstate}
432 { }
433
434 template<typename _Callable, typename... _Args,
435 typename = enable_if_t<!is_same_v<remove_cvref_t<_Callable>,
436 jthread>>>
437 explicit
438 jthread(_Callable&& __f, _Args&&... __args)
439 : _M_thread{_S_create(_M_stop_source, std::forward<_Callable>(__f),
440 std::forward<_Args>(__args)...)}
441 { }
442
443 jthread(const jthread&) = delete;
444 jthread(jthread&&) noexcept = default;
445
446 ~jthread()
447 {
448 if (joinable())
449 {
450 request_stop();
451 join();
452 }
453 }
454
455 jthread&
456 operator=(const jthread&) = delete;
457
458 jthread&
459 operator=(jthread&&) noexcept = default;
460
461 void
462 swap(jthread& __other) noexcept
463 {
464 std::swap(_M_stop_source, __other._M_stop_source);
465 std::swap(_M_thread, __other._M_thread);
466 }
467
468 [[nodiscard]] bool
469 joinable() const noexcept
470 {
471 return _M_thread.joinable();
472 }
473
474 void
475 join()
476 {
477 _M_thread.join();
478 }
479
480 void
481 detach()
482 {
483 _M_thread.detach();
484 }
485
486 [[nodiscard]] id
487 get_id() const noexcept
488 {
489 return _M_thread.get_id();
490 }
491
492 [[nodiscard]] native_handle_type
493 native_handle()
494 {
495 return _M_thread.native_handle();
496 }
497
498 [[nodiscard]] static unsigned
499 hardware_concurrency() noexcept
500 {
501 return thread::hardware_concurrency();
502 }
503
504 [[nodiscard]] stop_source
505 get_stop_source() noexcept
506 {
507 return _M_stop_source;
508 }
509
510 [[nodiscard]] stop_token
511 get_stop_token() const noexcept
512 {
513 return _M_stop_source.get_token();
514 }
515
516 bool request_stop() noexcept
517 {
518 return _M_stop_source.request_stop();
519 }
520
521 friend void swap(jthread& __lhs, jthread& __rhs) noexcept
522 {
523 __lhs.swap(__rhs);
524 }
525
526 private:
527 template<typename _Callable, typename... _Args>
528 static thread
529 _S_create(stop_source& __ssrc, _Callable&& __f, _Args&&... __args)
530 {
531 if constexpr(is_invocable_v<decay_t<_Callable>, stop_token,
532 decay_t<_Args>...>)
533 return thread{std::forward<_Callable>(__f), __ssrc.get_token(),
534 std::forward<_Args>(__args)...};
535 else
536 {
537 static_assert(is_invocable_v<decay_t<_Callable>,
538 decay_t<_Args>...>,
539 "std::thread arguments must be invocable after"
540 " conversion to rvalues");
541 return thread{std::forward<_Callable>(__f),
542 std::forward<_Args>(__args)...};
543 }
544 }
545
546 stop_source _M_stop_source;
547 thread _M_thread;
548 };
549 #endif // __cpp_lib_jthread
550
551 // @} group threads
552
553 _GLIBCXX_END_NAMESPACE_VERSION
554 } // namespace
555 #endif // C++11
556 #endif // _GLIBCXX_THREAD