libstdc++
thread
Go to the documentation of this file.
1 // <thread> -*- C++ -*-
2 
3 // Copyright (C) 2008-2021 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 #if __cplusplus > 201703L
41 # include <compare> // std::strong_ordering
42 # include <stop_token> // std::stop_source, std::stop_token, std::nostopstate
43 #endif
44 
45 #include <bits/std_thread.h> // std::thread, get_id, yield
46 
47 #ifdef _GLIBCXX_USE_NANOSLEEP
48 # include <cerrno> // errno, EINTR
49 # include <time.h> // nanosleep
50 #endif
51 
52 namespace std _GLIBCXX_VISIBILITY(default)
53 {
54 _GLIBCXX_BEGIN_NAMESPACE_VERSION
55 
56  /**
57  * @defgroup threads Threads
58  * @ingroup concurrency
59  *
60  * Classes for thread support.
61  * @{
62  */
63 
64  // std::thread is defined in <bits/std_thread.h>
65 
66 #if __cpp_lib_three_way_comparison
67  inline strong_ordering
68  operator<=>(thread::id __x, thread::id __y) noexcept
69  { return __x._M_thread <=> __y._M_thread; }
70 #else
71  inline bool
72  operator!=(thread::id __x, thread::id __y) noexcept
73  { return !(__x == __y); }
74 
75  inline bool
76  operator<(thread::id __x, thread::id __y) noexcept
77  {
78  // Pthreads doesn't define any way to do this, so we just have to
79  // assume native_handle_type is LessThanComparable.
80  return __x._M_thread < __y._M_thread;
81  }
82 
83  inline bool
84  operator<=(thread::id __x, thread::id __y) noexcept
85  { return !(__y < __x); }
86 
87  inline bool
88  operator>(thread::id __x, thread::id __y) noexcept
89  { return __y < __x; }
90 
91  inline bool
92  operator>=(thread::id __x, thread::id __y) noexcept
93  { return !(__x < __y); }
94 #endif // __cpp_lib_three_way_comparison
95 
96  template<class _CharT, class _Traits>
97  inline basic_ostream<_CharT, _Traits>&
98  operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
99  {
100  if (__id == thread::id())
101  return __out << "thread::id of a non-executing thread";
102  else
103  return __out << __id._M_thread;
104  }
105 
106  /** @namespace std::this_thread
107  * @brief ISO C++ 2011 namespace for interacting with the current thread
108  *
109  * C++11 30.3.2 [thread.thread.this] Namespace this_thread.
110  */
111  namespace this_thread
112  {
113 #ifndef _GLIBCXX_NO_SLEEP
114 
115 #ifndef _GLIBCXX_USE_NANOSLEEP
116  void
117  __sleep_for(chrono::seconds, chrono::nanoseconds);
118 #endif
119 
120  /// this_thread::sleep_for
121  template<typename _Rep, typename _Period>
122  inline void
123  sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
124  {
125  if (__rtime <= __rtime.zero())
126  return;
127  auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
128  auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
129 #ifdef _GLIBCXX_USE_NANOSLEEP
130  struct ::timespec __ts =
131  {
132  static_cast<std::time_t>(__s.count()),
133  static_cast<long>(__ns.count())
134  };
135  while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
136  { }
137 #else
138  __sleep_for(__s, __ns);
139 #endif
140  }
141 
142  /// this_thread::sleep_until
143  template<typename _Clock, typename _Duration>
144  inline void
145  sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
146  {
147 #if __cplusplus > 201703L
148  static_assert(chrono::is_clock_v<_Clock>);
149 #endif
150  auto __now = _Clock::now();
151  if (_Clock::is_steady)
152  {
153  if (__now < __atime)
154  sleep_for(__atime - __now);
155  return;
156  }
157  while (__now < __atime)
158  {
159  sleep_for(__atime - __now);
160  __now = _Clock::now();
161  }
162  }
163  } // namespace this_thread
164 #endif // ! NO_SLEEP
165 
166 #ifdef __cpp_lib_jthread
167 
168  /// A thread that can be requested to stop and automatically joined.
169  class jthread
170  {
171  public:
172  using id = thread::id;
173  using native_handle_type = thread::native_handle_type;
174 
175  jthread() noexcept
176  : _M_stop_source{nostopstate}
177  { }
178 
179  template<typename _Callable, typename... _Args,
180  typename = enable_if_t<!is_same_v<remove_cvref_t<_Callable>,
181  jthread>>>
182  explicit
183  jthread(_Callable&& __f, _Args&&... __args)
184  : _M_thread{_S_create(_M_stop_source, std::forward<_Callable>(__f),
185  std::forward<_Args>(__args)...)}
186  { }
187 
188  jthread(const jthread&) = delete;
189  jthread(jthread&&) noexcept = default;
190 
191  ~jthread()
192  {
193  if (joinable())
194  {
195  request_stop();
196  join();
197  }
198  }
199 
200  jthread&
201  operator=(const jthread&) = delete;
202 
203  jthread&
204  operator=(jthread&& __other) noexcept
205  {
206  std::jthread(std::move(__other)).swap(*this);
207  return *this;
208  }
209 
210  void
211  swap(jthread& __other) noexcept
212  {
213  std::swap(_M_stop_source, __other._M_stop_source);
214  std::swap(_M_thread, __other._M_thread);
215  }
216 
217  [[nodiscard]] bool
218  joinable() const noexcept
219  {
220  return _M_thread.joinable();
221  }
222 
223  void
224  join()
225  {
226  _M_thread.join();
227  }
228 
229  void
230  detach()
231  {
232  _M_thread.detach();
233  }
234 
235  [[nodiscard]] id
236  get_id() const noexcept
237  {
238  return _M_thread.get_id();
239  }
240 
241  [[nodiscard]] native_handle_type
242  native_handle()
243  {
244  return _M_thread.native_handle();
245  }
246 
247  [[nodiscard]] static unsigned
248  hardware_concurrency() noexcept
249  {
250  return thread::hardware_concurrency();
251  }
252 
253  [[nodiscard]] stop_source
254  get_stop_source() noexcept
255  {
256  return _M_stop_source;
257  }
258 
259  [[nodiscard]] stop_token
260  get_stop_token() const noexcept
261  {
262  return _M_stop_source.get_token();
263  }
264 
265  bool request_stop() noexcept
266  {
267  return _M_stop_source.request_stop();
268  }
269 
270  friend void swap(jthread& __lhs, jthread& __rhs) noexcept
271  {
272  __lhs.swap(__rhs);
273  }
274 
275  private:
276  template<typename _Callable, typename... _Args>
277  static thread
278  _S_create(stop_source& __ssrc, _Callable&& __f, _Args&&... __args)
279  {
280  if constexpr(is_invocable_v<decay_t<_Callable>, stop_token,
281  decay_t<_Args>...>)
282  return thread{std::forward<_Callable>(__f), __ssrc.get_token(),
283  std::forward<_Args>(__args)...};
284  else
285  {
286  static_assert(is_invocable_v<decay_t<_Callable>,
287  decay_t<_Args>...>,
288  "std::thread arguments must be invocable after"
289  " conversion to rvalues");
290  return thread{std::forward<_Callable>(__f),
291  std::forward<_Args>(__args)...};
292  }
293  }
294 
295  stop_source _M_stop_source;
296  thread _M_thread;
297  };
298 #endif // __cpp_lib_jthread
299 
300  // @} group threads
301 
302 _GLIBCXX_END_NAMESPACE_VERSION
303 } // namespace
304 #endif // C++11
305 #endif // _GLIBCXX_THREAD