1 // <thread> -*- C++ -*-
3 // Copyright (C) 2008-2024 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 #include <bits/requires_hosted.h> // concurrency
36 #if __cplusplus < 201103L
37 # include <bits/c++0x_warning.h>
40 #if __cplusplus > 201703L
41 # include <compare> // std::strong_ordering
42 # include <stop_token> // std::stop_source, std::stop_token, std::nostopstate
45 #if __cplusplus > 202002L
49 #include <bits/std_thread.h> // std::thread, get_id, yield
50 #include <bits/this_thread_sleep.h> // std::this_thread::sleep_for, sleep_until
52 #define __glibcxx_want_jthread
53 #define __glibcxx_want_formatters
54 #include <bits/version.h>
56 namespace std _GLIBCXX_VISIBILITY(default)
58 _GLIBCXX_BEGIN_NAMESPACE_VERSION
61 * @defgroup threads Threads
62 * @ingroup concurrency
65 * Classes for thread support.
69 // std::thread is defined in <bits/std_thread.h>
71 /// @relates std::thread::id @{
73 #if __cpp_lib_three_way_comparison
74 inline strong_ordering
75 operator<=>(thread::id __x, thread::id __y) noexcept
76 { return __x._M_thread <=> __y._M_thread; }
79 operator!=(thread::id __x, thread::id __y) noexcept
80 { return !(__x == __y); }
83 operator<(thread::id __x, thread::id __y) noexcept
85 // Pthreads doesn't define any way to do this, so we just have to
86 // assume native_handle_type is LessThanComparable.
87 return __x._M_thread < __y._M_thread;
91 operator<=(thread::id __x, thread::id __y) noexcept
92 { return !(__y < __x); }
95 operator>(thread::id __x, thread::id __y) noexcept
99 operator>=(thread::id __x, thread::id __y) noexcept
100 { return !(__x < __y); }
101 #endif // __cpp_lib_three_way_comparison
103 template<class _CharT, class _Traits>
104 inline basic_ostream<_CharT, _Traits>&
105 operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
107 if (__id == thread::id())
108 return __out << "thread::id of a non-executing thread";
110 return __out << __id._M_thread;
114 #ifdef __cpp_lib_jthread // C++ >= 20
116 /// @cond undocumented
117 #ifndef __STRICT_ANSI__
118 template<typename _Callable, typename... _Args>
119 constexpr bool __pmf_expects_stop_token = false;
121 template<typename _Callable, typename _Obj, typename... _Args>
122 constexpr bool __pmf_expects_stop_token<_Callable, _Obj, _Args...>
123 = __and_<is_member_function_pointer<remove_reference_t<_Callable>>,
124 is_invocable<_Callable, _Obj, stop_token, _Args...>>::value;
128 /** A thread with cancellation and automatic joining.
130 * Unlike `std::thread`, destroying a joinable `std::jthread` will not
131 * terminate the process. Instead, it will try to request its thread to
132 * stop, then will join it.
134 * A `std::jthread` has a `std::stop_source` member which will be passed
135 * as the first argument to the callable that runs in the new thread
136 * (as long as the callable will accept that argument). That can then
137 * be used to send a stop request that the new thread can test for.
145 using id = thread::id;
146 using native_handle_type = thread::native_handle_type;
149 : _M_stop_source{nostopstate}
152 template<typename _Callable, typename... _Args,
153 typename = enable_if_t<!is_same_v<remove_cvref_t<_Callable>,
156 jthread(_Callable&& __f, _Args&&... __args)
157 : _M_thread{_S_create(_M_stop_source, std::forward<_Callable>(__f),
158 std::forward<_Args>(__args)...)}
161 jthread(const jthread&) = delete;
162 jthread(jthread&&) noexcept = default;
174 operator=(const jthread&) = delete;
177 operator=(jthread&& __other) noexcept
179 std::jthread(std::move(__other)).swap(*this);
184 swap(jthread& __other) noexcept
186 std::swap(_M_stop_source, __other._M_stop_source);
187 std::swap(_M_thread, __other._M_thread);
191 joinable() const noexcept
193 return _M_thread.joinable();
209 get_id() const noexcept
211 return _M_thread.get_id();
214 [[nodiscard]] native_handle_type
217 return _M_thread.native_handle();
220 [[nodiscard]] static unsigned
221 hardware_concurrency() noexcept
223 return thread::hardware_concurrency();
226 [[nodiscard]] stop_source
227 get_stop_source() noexcept
229 return _M_stop_source;
232 [[nodiscard]] stop_token
233 get_stop_token() const noexcept
235 return _M_stop_source.get_token();
238 bool request_stop() noexcept
240 return _M_stop_source.request_stop();
243 friend void swap(jthread& __lhs, jthread& __rhs) noexcept
249 template<typename _Callable, typename... _Args>
251 _S_create(stop_source& __ssrc, _Callable&& __f, _Args&&... __args)
253 #ifndef __STRICT_ANSI__
254 if constexpr (__pmf_expects_stop_token<_Callable, _Args...>)
255 return _S_create_pmf(__ssrc, __f, std::forward<_Args>(__args)...);
258 if constexpr(is_invocable_v<decay_t<_Callable>, stop_token,
260 return thread{std::forward<_Callable>(__f), __ssrc.get_token(),
261 std::forward<_Args>(__args)...};
264 static_assert(is_invocable_v<decay_t<_Callable>,
266 "std::jthread arguments must be invocable after"
267 " conversion to rvalues");
268 return thread{std::forward<_Callable>(__f),
269 std::forward<_Args>(__args)...};
273 #ifndef __STRICT_ANSI__
274 template<typename _Callable, typename _Obj, typename... _Args>
276 _S_create_pmf(stop_source& __ssrc, _Callable __f, _Obj&& __obj,
279 return thread{__f, std::forward<_Obj>(__obj), __ssrc.get_token(),
280 std::forward<_Args>(__args)...};
284 stop_source _M_stop_source;
287 #endif // __cpp_lib_jthread
289 #ifdef __cpp_lib_formatters // C++ >= 23
291 template<typename _CharT>
292 class formatter<thread::id, _CharT>
295 constexpr typename basic_format_parse_context<_CharT>::iterator
296 parse(basic_format_parse_context<_CharT>& __pc)
298 __format::_Spec<_CharT> __spec{};
299 const auto __last = __pc.end();
300 auto __first = __pc.begin();
302 auto __finalize = [this, &__spec] {
306 auto __finished = [&] {
307 if (__first == __last || *__first == '}')
318 __first = __spec._M_parse_fill_and_align(__first, __last);
322 __first = __spec._M_parse_width(__first, __last, __pc);
326 __throw_format_error("format error: invalid format-spec for "
330 template<typename _Out>
331 typename basic_format_context<_Out, _CharT>::iterator
332 format(thread::id __id, basic_format_context<_Out, _CharT>& __fc) const
334 std::basic_ostringstream<_CharT> __os;
336 auto __str = __os.view();
337 return __format::__write_padded_as_spec(__str, __str.size(),
339 __format::_Align_right);
343 __format::_Spec<_CharT> _M_spec;
345 #endif // __cpp_lib_formatters
349 _GLIBCXX_END_NAMESPACE_VERSION
352 #endif // _GLIBCXX_THREAD