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