]> git.ipfire.org Git - thirdparty/gcc.git/blame - libstdc++-v3/include/std/thread
libstdc++: Remove redundant copying of std::async arguments [PR 69724]
[thirdparty/gcc.git] / libstdc++-v3 / include / std / thread
CommitLineData
46e113bf
CF
1// <thread> -*- C++ -*-
2
8d9254fc 3// Copyright (C) 2008-2020 Free Software Foundation, Inc.
46e113bf
CF
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
748086b7 8// Free Software Foundation; either version 3, or (at your option)
46e113bf
CF
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
748086b7
JJ
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/>.
46e113bf 24
f910786b 25/** @file include/thread
46e113bf
CF
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
734f5023 34#if __cplusplus < 201103L
ab65a4c7 35# include <bits/c++0x_warning.h>
46e113bf
CF
36#else
37
5bbb1f30
JW
38#include <chrono> // std::chrono::*
39
40#ifdef _GLIBCXX_USE_NANOSLEEP
41# include <cerrno> // errno, EINTR
42# include <time.h> // nanosleep
43#endif
ebc46494
JW
44
45#if defined(_GLIBCXX_HAS_GTHREADS)
46#include <bits/gthr.h>
47
ebc46494
JW
48#include <memory> // std::unique_ptr
49#include <tuple> // std::tuple
942c4b32
TR
50
51#if __cplusplus > 201703L
c7b591f3
JW
52# include <compare> // std::strong_ordering
53# include <stop_token> // std::stop_source, std::stop_token, std::nostopstate
942c4b32
TR
54#endif
55
ebc46494
JW
56#include <bits/functional_hash.h> // std::hash
57#include <bits/invoke.h> // std::__invoke
46e113bf 58
5bbb1f30
JW
59#endif // _GLIBCXX_HAS_GTHREADS
60
12ffa228
BK
61namespace std _GLIBCXX_VISIBILITY(default)
62{
63_GLIBCXX_BEGIN_NAMESPACE_VERSION
53dc5044 64
5b9daa7e
BK
65 /**
66 * @defgroup threads Threads
67 * @ingroup concurrency
68 *
69 * Classes for thread support.
70 * @{
71 */
72
5bbb1f30 73#if defined(_GLIBCXX_HAS_GTHREADS)
d7afcd2b 74 /// thread
8644ecf5 75 class thread
46e113bf
CF
76 {
77 public:
ce535a96
JW
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
626dda69 87 typedef __gthread_t native_handle_type;
d7afcd2b
BK
88
89 /// thread::id
90 class id
46e113bf 91 {
626dda69 92 native_handle_type _M_thread;
d7afcd2b 93
46e113bf 94 public:
7f0d79d5 95 id() noexcept : _M_thread() { }
d7afcd2b
BK
96
97 explicit
98 id(native_handle_type __id) : _M_thread(__id) { }
99
100 private:
101 friend class thread;
0e5abeb0 102 friend struct hash<id>;
d7afcd2b
BK
103
104 friend bool
c7b591f3 105 operator==(id __x, id __y) noexcept;
d7afcd2b 106
c7b591f3
JW
107#if __cpp_lib_three_way_comparison
108 friend strong_ordering
109 operator<=>(id __x, id __y) noexcept;
110#else
d7afcd2b 111 friend bool
c7b591f3
JW
112 operator<(id __x, id __y) noexcept;
113#endif
d7afcd2b
BK
114
115 template<class _CharT, class _Traits>
116 friend basic_ostream<_CharT, _Traits>&
c7b591f3 117 operator<<(basic_ostream<_CharT, _Traits>& __out, id __id);
d7afcd2b
BK
118 };
119
d7afcd2b 120 private:
626dda69 121 id _M_id;
d7afcd2b 122
1b5dc776
JW
123 // _GLIBCXX_RESOLVE_LIB_DEFECTS
124 // 2097. packaged_task constructors should be constrained
cb4f9a8c 125 // 3039. Unnecessary decay in thread and packaged_task
d49b3426
JW
126 template<typename _Tp>
127 using __not_same = __not_<is_same<__remove_cvref_t<_Tp>, thread>>;
d7afcd2b 128
d49b3426
JW
129 public:
130 thread() noexcept = default;
d7afcd2b 131
d49b3426
JW
132 template<typename _Callable, typename... _Args,
133 typename = _Require<__not_same<_Callable>>>
33ac58d5 134 explicit
46e113bf 135 thread(_Callable&& __f, _Args&&... __args)
1b3fad81 136 {
d49b3426
JW
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
c6b3f349 142#ifdef GTHR_ACTIVE_PROXY
ce535a96
JW
143 // Create a reference to pthread_create, not just the gthr weak symbol.
144 auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
c6b3f349 145#else
ce535a96 146 auto __depend = nullptr;
c6b3f349 147#endif
bb1b7f08
JW
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)...)),
ce535a96 153 __depend);
1b3fad81 154 }
46e113bf 155
959d14e1 156 ~thread()
cbdab9c8
JW
157 {
158 if (joinable())
cd3b0faf 159 std::terminate();
cbdab9c8 160 }
46e113bf 161
d49b3426
JW
162 thread(const thread&) = delete;
163
164 thread(thread&& __t) noexcept
165 { swap(__t); }
166
46e113bf 167 thread& operator=(const thread&) = delete;
d7afcd2b 168
7f0d79d5 169 thread& operator=(thread&& __t) noexcept
78b580a9
JW
170 {
171 if (joinable())
cd3b0faf 172 std::terminate();
78b580a9
JW
173 swap(__t);
174 return *this;
175 }
46e113bf 176
d7afcd2b 177 void
7f0d79d5 178 swap(thread& __t) noexcept
626dda69 179 { std::swap(_M_id, __t._M_id); }
46e113bf 180
d7afcd2b 181 bool
7f0d79d5 182 joinable() const noexcept
626dda69 183 { return !(_M_id == id()); }
46e113bf 184
d7afcd2b 185 void
46e113bf
CF
186 join();
187
d7afcd2b 188 void
46e113bf
CF
189 detach();
190
c7b591f3 191 id
7f0d79d5 192 get_id() const noexcept
626dda69 193 { return _M_id; }
46e113bf 194
cbdab9c8
JW
195 /** @pre thread is joinable
196 */
d7afcd2b 197 native_handle_type
46e113bf 198 native_handle()
626dda69 199 { return _M_id._M_thread; }
46e113bf 200
d7afcd2b
BK
201 // Returns a value that hints at the number of hardware thread contexts.
202 static unsigned int
43653c33 203 hardware_concurrency() noexcept;
46e113bf 204
46e113bf 205 private:
ce535a96
JW
206 template<typename _Callable>
207 struct _State_impl : public _State
208 {
209 _Callable _M_func;
210
8db7a05f
JW
211 template<typename... _Args>
212 _State_impl(_Args&&... __args)
213 : _M_func{{std::forward<_Args>(__args)...}}
214 { }
ce535a96
JW
215
216 void
217 _M_run() { _M_func(); }
218 };
c6b3f349 219
626dda69 220 void
ce535a96 221 _M_start_thread(_State_ptr, void (*)());
626dda69 222
ce535a96
JW
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 };
46e113bf 233
ce535a96
JW
234 private:
235 void
236 _M_start_thread(__shared_base_type, void (*)());
237
238 void
239 _M_start_thread(__shared_base_type);
240#endif
5579170b
JW
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
d49b3426
JW
249 template<typename>
250 struct __result;
251 template<typename _Fn, typename... _Args>
252 struct __result<tuple<_Fn, _Args...>>
253 : __invoke_result<_Fn, _Args...>
254 { };
5579170b
JW
255
256 template<size_t... _Ind>
d49b3426 257 typename __result<_Tuple>::type
5579170b 258 _M_invoke(_Index_tuple<_Ind...>)
5579170b
JW
259 { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
260
d49b3426 261 typename __result<_Tuple>::type
5579170b 262 operator()()
d49b3426
JW
263 {
264 using _Indices
265 = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
266 return _M_invoke(_Indices());
267 }
5579170b
JW
268 };
269
5579170b 270 public:
bb1b7f08
JW
271 template<typename... _Tp>
272 using _Call_wrapper = _Invoker<tuple<typename decay<_Tp>::type...>>;
ce535a96 273 };
d5545744 274
46e113bf 275 inline void
7f0d79d5 276 swap(thread& __x, thread& __y) noexcept
46e113bf
CF
277 { __x.swap(__y); }
278
b05cf382
JW
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
c7b591f3
JW
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
d7afcd2b 294 inline bool
7f0d79d5 295 operator!=(thread::id __x, thread::id __y) noexcept
d7afcd2b
BK
296 { return !(__x == __y); }
297
b05cf382
JW
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
d7afcd2b 306 inline bool
7f0d79d5 307 operator<=(thread::id __x, thread::id __y) noexcept
d7afcd2b
BK
308 { return !(__y < __x); }
309
310 inline bool
7f0d79d5 311 operator>(thread::id __x, thread::id __y) noexcept
d7afcd2b
BK
312 { return __y < __x; }
313
314 inline bool
7f0d79d5 315 operator>=(thread::id __x, thread::id __y) noexcept
d7afcd2b 316 { return !(__x < __y); }
c7b591f3 317#endif // __cpp_lib_three_way_comparison
d7afcd2b 318
5c8db18a
PC
319 // DR 889.
320 /// std::hash specialization for thread::id.
321 template<>
322 struct hash<thread::id>
5d64ee19 323 : public __hash_base<size_t, thread::id>
5c8db18a
PC
324 {
325 size_t
72f1c34b 326 operator()(const thread::id& __id) const noexcept
e7f72940 327 { return std::_Hash_impl::hash(__id._M_thread); }
5c8db18a
PC
328 };
329
d7afcd2b
BK
330 template<class _CharT, class _Traits>
331 inline basic_ostream<_CharT, _Traits>&
ff74fd13 332 operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
d7afcd2b
BK
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 }
5bbb1f30 339#endif // _GLIBCXX_HAS_GTHREADS
d7afcd2b 340
5b9daa7e 341 /** @namespace std::this_thread
19aaf814
JW
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.
5b9daa7e 345 */
46e113bf
CF
346 namespace this_thread
347 {
5bbb1f30 348#if defined _GLIBCXX_HAS_GTHREADS
f7459b6c 349 /// get_id
4a50cd93 350 inline thread::id
755be51d
JW
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 }
5bbb1f30 363#endif // _GLIBCXX_HAS_GTHREADS
46e113bf 364
f7459b6c 365 /// yield
959d14e1 366 inline void
7f0d79d5 367 yield() noexcept
aa66b299 368 {
5bbb1f30 369#if defined _GLIBCXX_HAS_GTHREADS && defined _GLIBCXX_USE_SCHED_YIELD
aa66b299 370 __gthread_yield();
959d14e1 371#endif
aa66b299
JW
372 }
373
374 void
375 __sleep_for(chrono::seconds, chrono::nanoseconds);
46e113bf 376
f7459b6c 377 /// sleep_for
46e113bf 378 template<typename _Rep, typename _Period>
959d14e1 379 inline void
46e113bf
CF
380 sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
381 {
d1a74a28
JW
382 if (__rtime <= __rtime.zero())
383 return;
aa66b299
JW
384 auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
385 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
386#ifdef _GLIBCXX_USE_NANOSLEEP
5bbb1f30 387 struct ::timespec __ts =
46e113bf
CF
388 {
389 static_cast<std::time_t>(__s.count()),
390 static_cast<long>(__ns.count())
391 };
f55e699d
JW
392 while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
393 { }
aa66b299
JW
394#else
395 __sleep_for(__s, __ns);
396#endif
46e113bf 397 }
d1129441
JW
398
399 /// sleep_until
400 template<typename _Clock, typename _Duration>
401 inline void
402 sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
d1a74a28 403 {
bf1fc37b
JW
404#if __cplusplus > 201703L
405 static_assert(chrono::is_clock_v<_Clock>);
406#endif
d1a74a28 407 auto __now = _Clock::now();
f55e699d
JW
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 }
d1a74a28 419 }
46e113bf 420 }
5b9daa7e 421
942c4b32
TR
422#ifdef __cpp_lib_jthread
423
424 class jthread
425 {
426 public:
c7b591f3
JW
427 using id = thread::id;
428 using native_handle_type = thread::native_handle_type;
942c4b32
TR
429
430 jthread() noexcept
74533764 431 : _M_stop_source{nostopstate}
942c4b32
TR
432 { }
433
434 template<typename _Callable, typename... _Args,
74533764
JW
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 { }
942c4b32
TR
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
74533764 468 [[nodiscard]] bool
942c4b32
TR
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
74533764 486 [[nodiscard]] id
942c4b32
TR
487 get_id() const noexcept
488 {
ebc46494 489 return _M_thread.get_id();
942c4b32
TR
490 }
491
74533764 492 [[nodiscard]] native_handle_type
942c4b32
TR
493 native_handle()
494 {
495 return _M_thread.native_handle();
496 }
497
74533764 498 [[nodiscard]] static unsigned
942c4b32
TR
499 hardware_concurrency() noexcept
500 {
c7b591f3 501 return thread::hardware_concurrency();
942c4b32
TR
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 {
ebc46494 518 return _M_stop_source.request_stop();
942c4b32
TR
519 }
520
74533764
JW
521 friend void swap(jthread& __lhs, jthread& __rhs) noexcept
522 {
523 __lhs.swap(__rhs);
524 }
525
942c4b32 526 private:
74533764
JW
527 template<typename _Callable, typename... _Args>
528 static thread
529 _S_create(stop_source& __ssrc, _Callable&& __f, _Args&&... __args)
530 {
ebc46494
JW
531 if constexpr(is_invocable_v<decay_t<_Callable>, stop_token,
532 decay_t<_Args>...>)
74533764
JW
533 return thread{std::forward<_Callable>(__f), __ssrc.get_token(),
534 std::forward<_Args>(__args)...};
535 else
ebc46494
JW
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 }
74533764
JW
544 }
545
942c4b32 546 stop_source _M_stop_source;
c7b591f3 547 thread _M_thread;
942c4b32
TR
548 };
549#endif // __cpp_lib_jthread
5bbb1f30
JW
550
551 // @} group threads
552
4a15d842 553_GLIBCXX_END_NAMESPACE_VERSION
12ffa228 554} // namespace
734f5023 555#endif // C++11
46e113bf 556#endif // _GLIBCXX_THREAD