| 1 | // <thread> -*- C++ -*- |
| 2 | |
| 3 | // Copyright (C) 2008-2025 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 | #ifdef _GLIBCXX_SYSHDR |
| 33 | #pragma GCC system_header |
| 34 | #endif |
| 35 | |
| 36 | #include <bits/requires_hosted.h> // concurrency |
| 37 | |
| 38 | #if __cplusplus < 201103L |
| 39 | # include <bits/c++0x_warning.h> |
| 40 | #else |
| 41 | |
| 42 | #if __cplusplus > 201703L |
| 43 | # include <compare> // std::strong_ordering |
| 44 | # include <stop_token> // std::stop_source, std::stop_token, std::nostopstate |
| 45 | #endif |
| 46 | |
| 47 | #include <bits/std_thread.h> // std::thread, get_id, yield |
| 48 | #include <bits/this_thread_sleep.h> // std::this_thread::sleep_for, sleep_until |
| 49 | |
| 50 | #define __glibcxx_want_jthread |
| 51 | #define __glibcxx_want_formatters |
| 52 | #include <bits/version.h> |
| 53 | |
| 54 | #if __cpp_lib_formatters |
| 55 | # include <format> |
| 56 | #endif |
| 57 | |
| 58 | namespace std _GLIBCXX_VISIBILITY(default) |
| 59 | { |
| 60 | _GLIBCXX_BEGIN_NAMESPACE_VERSION |
| 61 | |
| 62 | /** |
| 63 | * @defgroup threads Threads |
| 64 | * @ingroup concurrency |
| 65 | * @since C++11 |
| 66 | * |
| 67 | * Classes for thread support. |
| 68 | * @{ |
| 69 | */ |
| 70 | |
| 71 | // std::thread is defined in <bits/std_thread.h> |
| 72 | |
| 73 | /// @relates std::thread::id @{ |
| 74 | |
| 75 | #if __cpp_lib_three_way_comparison |
| 76 | inline strong_ordering |
| 77 | operator<=>(thread::id __x, thread::id __y) noexcept |
| 78 | { return __x._M_thread <=> __y._M_thread; } |
| 79 | #else |
| 80 | inline bool |
| 81 | operator!=(thread::id __x, thread::id __y) noexcept |
| 82 | { return !(__x == __y); } |
| 83 | |
| 84 | inline bool |
| 85 | operator<(thread::id __x, thread::id __y) noexcept |
| 86 | { |
| 87 | // Pthreads doesn't define any way to do this, so we just have to |
| 88 | // assume native_handle_type is LessThanComparable. |
| 89 | return __x._M_thread < __y._M_thread; |
| 90 | } |
| 91 | |
| 92 | inline bool |
| 93 | operator<=(thread::id __x, thread::id __y) noexcept |
| 94 | { return !(__y < __x); } |
| 95 | |
| 96 | inline bool |
| 97 | operator>(thread::id __x, thread::id __y) noexcept |
| 98 | { return __y < __x; } |
| 99 | |
| 100 | inline bool |
| 101 | operator>=(thread::id __x, thread::id __y) noexcept |
| 102 | { return !(__x < __y); } |
| 103 | #endif // __cpp_lib_three_way_comparison |
| 104 | |
| 105 | template<class _CharT, class _Traits> |
| 106 | inline basic_ostream<_CharT, _Traits>& |
| 107 | operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id) |
| 108 | { |
| 109 | // Convert non-void pointers to const void* for formatted output. |
| 110 | using __output_type |
| 111 | = __conditional_t<is_pointer<thread::native_handle_type>::value, |
| 112 | const void*, |
| 113 | thread::native_handle_type>; |
| 114 | |
| 115 | if (__id == thread::id()) |
| 116 | return __out << "thread::id of a non-executing thread" ; |
| 117 | else |
| 118 | return __out << static_cast<__output_type>(__id._M_thread); |
| 119 | } |
| 120 | /// @} |
| 121 | |
| 122 | #ifdef __cpp_lib_jthread // C++ >= 20 |
| 123 | |
| 124 | /// @cond undocumented |
| 125 | #ifndef __STRICT_ANSI__ |
| 126 | // As an extension we support invoking a pointer-to-member-function that |
| 127 | // expects a stop_token as the first argument. See PR libstdc++/100612. |
| 128 | template<typename _Callable, typename... _Args> |
| 129 | constexpr bool __pmf_expects_stop_token = false; |
| 130 | |
| 131 | template<typename _Callable, typename _Obj, typename... _Args> |
| 132 | requires is_member_function_pointer_v<remove_reference_t<_Callable>> |
| 133 | constexpr bool __pmf_expects_stop_token<_Callable, _Obj, _Args...> |
| 134 | = is_invocable_v<_Callable, _Obj, stop_token, _Args...>; |
| 135 | #endif |
| 136 | /// @endcond |
| 137 | |
| 138 | /** A thread with cancellation and automatic joining. |
| 139 | * |
| 140 | * Unlike `std::thread`, destroying a joinable `std::jthread` will not |
| 141 | * terminate the process. Instead, it will try to request its thread to |
| 142 | * stop, then will join it. |
| 143 | * |
| 144 | * A `std::jthread` has a `std::stop_source` member which will be passed |
| 145 | * as the first argument to the callable that runs in the new thread |
| 146 | * (as long as the callable will accept that argument). That can then |
| 147 | * be used to send a stop request that the new thread can test for. |
| 148 | * |
| 149 | * @headerfile thread |
| 150 | * @since C++20 |
| 151 | */ |
| 152 | class jthread |
| 153 | { |
| 154 | public: |
| 155 | using id = thread::id; |
| 156 | using native_handle_type = thread::native_handle_type; |
| 157 | |
| 158 | jthread() noexcept |
| 159 | : _M_stop_source{nostopstate} |
| 160 | { } |
| 161 | |
| 162 | template<typename _Callable, typename... _Args, |
| 163 | typename = enable_if_t<!is_same_v<remove_cvref_t<_Callable>, |
| 164 | jthread>>> |
| 165 | explicit |
| 166 | jthread(_Callable&& __f, _Args&&... __args) |
| 167 | : _M_thread{_S_create(_M_stop_source, std::forward<_Callable>(__f), |
| 168 | std::forward<_Args>(__args)...)} |
| 169 | { } |
| 170 | |
| 171 | jthread(const jthread&) = delete; |
| 172 | jthread(jthread&&) noexcept = default; |
| 173 | |
| 174 | ~jthread() |
| 175 | { |
| 176 | if (joinable()) |
| 177 | { |
| 178 | request_stop(); |
| 179 | join(); |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | jthread& |
| 184 | operator=(const jthread&) = delete; |
| 185 | |
| 186 | jthread& |
| 187 | operator=(jthread&& __other) noexcept |
| 188 | { |
| 189 | std::jthread(std::move(__other)).swap(other&: *this); |
| 190 | return *this; |
| 191 | } |
| 192 | |
| 193 | void |
| 194 | swap(jthread& __other) noexcept |
| 195 | { |
| 196 | std::swap(a&: _M_stop_source, b&: __other._M_stop_source); |
| 197 | std::swap(x&: _M_thread, y&: __other._M_thread); |
| 198 | } |
| 199 | |
| 200 | [[nodiscard]] bool |
| 201 | joinable() const noexcept |
| 202 | { |
| 203 | return _M_thread.joinable(); |
| 204 | } |
| 205 | |
| 206 | void |
| 207 | join() |
| 208 | { |
| 209 | _M_thread.join(); |
| 210 | } |
| 211 | |
| 212 | void |
| 213 | detach() |
| 214 | { |
| 215 | _M_thread.detach(); |
| 216 | } |
| 217 | |
| 218 | [[nodiscard]] id |
| 219 | get_id() const noexcept |
| 220 | { |
| 221 | return _M_thread.get_id(); |
| 222 | } |
| 223 | |
| 224 | [[nodiscard]] native_handle_type |
| 225 | native_handle() |
| 226 | { |
| 227 | return _M_thread.native_handle(); |
| 228 | } |
| 229 | |
| 230 | [[nodiscard]] static unsigned |
| 231 | hardware_concurrency() noexcept |
| 232 | { |
| 233 | return thread::hardware_concurrency(); |
| 234 | } |
| 235 | |
| 236 | [[nodiscard]] stop_source |
| 237 | get_stop_source() noexcept |
| 238 | { |
| 239 | return _M_stop_source; |
| 240 | } |
| 241 | |
| 242 | [[nodiscard]] stop_token |
| 243 | get_stop_token() const noexcept |
| 244 | { |
| 245 | return _M_stop_source.get_token(); |
| 246 | } |
| 247 | |
| 248 | bool request_stop() noexcept |
| 249 | { |
| 250 | return _M_stop_source.request_stop(); |
| 251 | } |
| 252 | |
| 253 | friend void swap(jthread& __lhs, jthread& __rhs) noexcept |
| 254 | { |
| 255 | __lhs.swap(other&: __rhs); |
| 256 | } |
| 257 | |
| 258 | private: |
| 259 | template<typename _Callable, typename... _Args> |
| 260 | static thread |
| 261 | _S_create(stop_source& __ssrc, _Callable&& __f, _Args&&... __args) |
| 262 | { |
| 263 | #ifndef __STRICT_ANSI__ |
| 264 | if constexpr (__pmf_expects_stop_token<_Callable, _Args...>) |
| 265 | return _S_create_pmf(__ssrc, __f, std::forward<_Args>(__args)...); |
| 266 | else |
| 267 | #endif |
| 268 | if constexpr(is_invocable_v<decay_t<_Callable>, stop_token, |
| 269 | decay_t<_Args>...>) |
| 270 | return thread{std::forward<_Callable>(__f), __ssrc.get_token(), |
| 271 | std::forward<_Args>(__args)...}; |
| 272 | else |
| 273 | { |
| 274 | static_assert(is_invocable_v<decay_t<_Callable>, |
| 275 | decay_t<_Args>...>, |
| 276 | "std::jthread arguments must be invocable after" |
| 277 | " conversion to rvalues" ); |
| 278 | return thread{std::forward<_Callable>(__f), |
| 279 | std::forward<_Args>(__args)...}; |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | #ifndef __STRICT_ANSI__ |
| 284 | template<typename _Callable, typename _Obj, typename... _Args> |
| 285 | static thread |
| 286 | _S_create_pmf(stop_source& __ssrc, _Callable __f, _Obj&& __obj, |
| 287 | _Args&&... __args) |
| 288 | { |
| 289 | return thread{__f, std::forward<_Obj>(__obj), __ssrc.get_token(), |
| 290 | std::forward<_Args>(__args)...}; |
| 291 | } |
| 292 | #endif |
| 293 | |
| 294 | stop_source _M_stop_source; |
| 295 | thread _M_thread; |
| 296 | }; |
| 297 | #endif // __cpp_lib_jthread |
| 298 | |
| 299 | #ifdef __cpp_lib_formatters // C++ >= 23 |
| 300 | template<typename _CharT> |
| 301 | requires is_pointer_v<thread::native_handle_type> |
| 302 | || is_integral_v<thread::native_handle_type> |
| 303 | class formatter<thread::id, _CharT> |
| 304 | { |
| 305 | public: |
| 306 | constexpr typename basic_format_parse_context<_CharT>::iterator |
| 307 | parse(basic_format_parse_context<_CharT>& __pc) |
| 308 | { |
| 309 | __format::_Spec<_CharT> __spec{}; |
| 310 | const auto __last = __pc.end(); |
| 311 | auto __first = __pc.begin(); |
| 312 | |
| 313 | auto __finalize = [this, &__spec] { |
| 314 | _M_spec = __spec; |
| 315 | }; |
| 316 | |
| 317 | auto __finished = [&] { |
| 318 | if (__first == __last || *__first == '}') |
| 319 | { |
| 320 | __finalize(); |
| 321 | return true; |
| 322 | } |
| 323 | return false; |
| 324 | }; |
| 325 | |
| 326 | if (__finished()) |
| 327 | return __first; |
| 328 | |
| 329 | __first = __spec._M_parse_fill_and_align(__first, __last); |
| 330 | if (__finished()) |
| 331 | return __first; |
| 332 | |
| 333 | __first = __spec._M_parse_width(__first, __last, __pc); |
| 334 | if (__finished()) |
| 335 | return __first; |
| 336 | |
| 337 | __throw_format_error("format error: invalid format-spec for " |
| 338 | "std::thread::id" ); |
| 339 | } |
| 340 | |
| 341 | template<typename _Out> |
| 342 | typename basic_format_context<_Out, _CharT>::iterator |
| 343 | format(thread::id __id, basic_format_context<_Out, _CharT>& __fc) const |
| 344 | { |
| 345 | basic_string_view<_CharT> __sv; |
| 346 | if constexpr (is_same_v<_CharT, char>) |
| 347 | __sv = "{}thread::id of a non-executing thread" ; |
| 348 | else |
| 349 | __sv = L"{}thread::id of a non-executing thread" ; |
| 350 | basic_string<_CharT> __str; |
| 351 | if (__id == thread::id()) |
| 352 | __sv.remove_prefix(2); |
| 353 | else |
| 354 | { |
| 355 | using _FmtStr = __format::_Runtime_format_string<_CharT>; |
| 356 | // Convert non-void pointers to const void* for formatted output. |
| 357 | using __output_type |
| 358 | = __conditional_t<is_pointer_v<thread::native_handle_type>, |
| 359 | const void*, |
| 360 | thread::native_handle_type>; |
| 361 | auto __o = static_cast<__output_type>(__id._M_thread); |
| 362 | __sv = __str = std::format(_FmtStr(__sv.substr(0, 2)), __o); |
| 363 | } |
| 364 | return __format::__write_padded_as_spec(__sv, __sv.size(), |
| 365 | __fc, _M_spec, |
| 366 | __format::_Align_right); |
| 367 | } |
| 368 | |
| 369 | private: |
| 370 | __format::_Spec<_CharT> _M_spec; |
| 371 | }; |
| 372 | #endif // __cpp_lib_formatters |
| 373 | |
| 374 | /// @} group threads |
| 375 | |
| 376 | _GLIBCXX_END_NAMESPACE_VERSION |
| 377 | } // namespace |
| 378 | #endif // C++11 |
| 379 | #endif // _GLIBCXX_THREAD |
| 380 | |