1// <thread> -*- 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 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#if __cplusplus > 201703L
39# include <compare> // std::strong_ordering
40# include <stop_token> // std::stop_source, std::stop_token, std::nostopstate
41#endif
42
43#include <bits/std_thread.h> // std::thread, get_id, yield
44#include <bits/this_thread_sleep.h> // std::this_thread::sleep_for, sleep_until
45
46namespace std _GLIBCXX_VISIBILITY(default)
47{
48_GLIBCXX_BEGIN_NAMESPACE_VERSION
49
50 /**
51 * @defgroup threads Threads
52 * @ingroup concurrency
53 * @since C++11
54 *
55 * Classes for thread support.
56 * @{
57 */
58
59 // std::thread is defined in <bits/std_thread.h>
60
61 /// @relates std::thread::id @{
62
63#if __cpp_lib_three_way_comparison
64 inline strong_ordering
65 operator<=>(thread::id __x, thread::id __y) noexcept
66 { return __x._M_thread <=> __y._M_thread; }
67#else
68 inline bool
69 operator!=(thread::id __x, thread::id __y) noexcept
70 { return !(__x == __y); }
71
72 inline bool
73 operator<(thread::id __x, thread::id __y) noexcept
74 {
75 // Pthreads doesn't define any way to do this, so we just have to
76 // assume native_handle_type is LessThanComparable.
77 return __x._M_thread < __y._M_thread;
78 }
79
80 inline bool
81 operator<=(thread::id __x, thread::id __y) noexcept
82 { return !(__y < __x); }
83
84 inline bool
85 operator>(thread::id __x, thread::id __y) noexcept
86 { return __y < __x; }
87
88 inline bool
89 operator>=(thread::id __x, thread::id __y) noexcept
90 { return !(__x < __y); }
91#endif // __cpp_lib_three_way_comparison
92
93 template<class _CharT, class _Traits>
94 inline basic_ostream<_CharT, _Traits>&
95 operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
96 {
97 if (__id == thread::id())
98 return __out << "thread::id of a non-executing thread";
99 else
100 return __out << __id._M_thread;
101 }
102 /// @}
103
104#ifdef __cpp_lib_jthread
105
106 /// @cond undocumented
107#ifndef __STRICT_ANSI__
108 template<typename _Callable, typename... _Args>
109 constexpr bool __pmf_expects_stop_token = false;
110
111 template<typename _Callable, typename _Obj, typename... _Args>
112 constexpr bool __pmf_expects_stop_token<_Callable, _Obj, _Args...>
113 = __and_<is_member_function_pointer<remove_reference_t<_Callable>>,
114 is_invocable<_Callable, _Obj, stop_token, _Args...>>::value;
115#endif
116 /// @endcond
117
118 /** A thread with cancellation and automatic joining.
119 *
120 * Unlike `std::thread`, destroying a joinable `std::jthread` will not
121 * terminate the process. Instead, it will try to request its thread to
122 * stop, then will join it.
123 *
124 * A `std::jthread` has a `std::stop_source` member which will be passed
125 * as the first argument to the callable that runs in the new thread
126 * (as long as the callable will accept that argument). That can then
127 * be used to send a stop request that the new thread can test for.
128 *
129 * @headerfile thread
130 * @since C++20
131 */
132 class jthread
133 {
134 public:
135 using id = thread::id;
136 using native_handle_type = thread::native_handle_type;
137
138 jthread() noexcept
139 : _M_stop_source{nostopstate}
140 { }
141
142 template<typename _Callable, typename... _Args,
143 typename = enable_if_t<!is_same_v<remove_cvref_t<_Callable>,
144 jthread>>>
145 explicit
146 jthread(_Callable&& __f, _Args&&... __args)
147 : _M_thread{_S_create(_M_stop_source, std::forward<_Callable>(__f),
148 std::forward<_Args>(__args)...)}
149 { }
150
151 jthread(const jthread&) = delete;
152 jthread(jthread&&) noexcept = default;
153
154 ~jthread()
155 {
156 if (joinable())
157 {
158 request_stop();
159 join();
160 }
161 }
162
163 jthread&
164 operator=(const jthread&) = delete;
165
166 jthread&
167 operator=(jthread&& __other) noexcept
168 {
169 std::jthread(std::move(__other)).swap(*this);
170 return *this;
171 }
172
173 void
174 swap(jthread& __other) noexcept
175 {
176 std::swap(_M_stop_source, __other._M_stop_source);
177 std::swap(_M_thread, __other._M_thread);
178 }
179
180 [[nodiscard]] bool
181 joinable() const noexcept
182 {
183 return _M_thread.joinable();
184 }
185
186 void
187 join()
188 {
189 _M_thread.join();
190 }
191
192 void
193 detach()
194 {
195 _M_thread.detach();
196 }
197
198 [[nodiscard]] id
199 get_id() const noexcept
200 {
201 return _M_thread.get_id();
202 }
203
204 [[nodiscard]] native_handle_type
205 native_handle()
206 {
207 return _M_thread.native_handle();
208 }
209
210 [[nodiscard]] static unsigned
211 hardware_concurrency() noexcept
212 {
213 return thread::hardware_concurrency();
214 }
215
216 [[nodiscard]] stop_source
217 get_stop_source() noexcept
218 {
219 return _M_stop_source;
220 }
221
222 [[nodiscard]] stop_token
223 get_stop_token() const noexcept
224 {
225 return _M_stop_source.get_token();
226 }
227
228 bool request_stop() noexcept
229 {
230 return _M_stop_source.request_stop();
231 }
232
233 friend void swap(jthread& __lhs, jthread& __rhs) noexcept
234 {
235 __lhs.swap(__rhs);
236 }
237
238 private:
239 template<typename _Callable, typename... _Args>
240 static thread
241 _S_create(stop_source& __ssrc, _Callable&& __f, _Args&&... __args)
242 {
243#ifndef __STRICT_ANSI__
244 if constexpr (__pmf_expects_stop_token<_Callable, _Args...>)
245 return _S_create_pmf(__ssrc, __f, std::forward<_Args>(__args)...);
246 else
247#endif
248 if constexpr(is_invocable_v<decay_t<_Callable>, stop_token,
249 decay_t<_Args>...>)
250 return thread{std::forward<_Callable>(__f), __ssrc.get_token(),
251 std::forward<_Args>(__args)...};
252 else
253 {
254 static_assert(is_invocable_v<decay_t<_Callable>,
255 decay_t<_Args>...>,
256 "std::jthread arguments must be invocable after"
257 " conversion to rvalues");
258 return thread{std::forward<_Callable>(__f),
259 std::forward<_Args>(__args)...};
260 }
261 }
262
263#ifndef __STRICT_ANSI__
264 template<typename _Callable, typename _Obj, typename... _Args>
265 static thread
266 _S_create_pmf(stop_source& __ssrc, _Callable __f, _Obj&& __obj,
267 _Args&&... __args)
268 {
269 return thread{__f, std::forward<_Obj>(__obj), __ssrc.get_token(),
270 std::forward<_Args>(__args)...};
271 }
272#endif
273
274 stop_source _M_stop_source;
275 thread _M_thread;
276 };
277#endif // __cpp_lib_jthread
278
279 /// @} group threads
280
281_GLIBCXX_END_NAMESPACE_VERSION
282} // namespace
283#endif // C++11
284#endif // _GLIBCXX_THREAD
285