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 <bits/c++config.h>
39 
40 #if defined(_GLIBCXX_HAS_GTHREADS)
41 #include <bits/gthr.h>
42 
43 #include <chrono> // std::chrono::*
44 #include <memory> // std::unique_ptr
45 #include <tuple> // std::tuple
46 
47 #if __cplusplus > 201703L
48 # include <stop_token> // std::stop_source, std::stop_token, std::nostopstate
49 #endif
50 
51 #ifdef _GLIBCXX_USE_NANOSLEEP
52 # include <cerrno> // errno, EINTR
53 # include <time.h> // nanosleep
54 #endif
55 
56 #include <bits/functional_hash.h> // std::hash
57 #include <bits/invoke.h> // std::__invoke
58 
59 namespace std _GLIBCXX_VISIBILITY(default)
60 {
61 _GLIBCXX_BEGIN_NAMESPACE_VERSION
62 
63  /**
64  * @defgroup threads Threads
65  * @ingroup concurrency
66  *
67  * Classes for thread support.
68  * @{
69  */
70 
71  /// thread
72  class thread
73  {
74  public:
75  // Abstract base class for types that wrap arbitrary functors to be
76  // invoked in the new thread of execution.
77  struct _State
78  {
79  virtual ~_State();
80  virtual void _M_run() = 0;
81  };
83 
84  typedef __gthread_t native_handle_type;
85 
86  /// thread::id
87  class id
88  {
89  native_handle_type _M_thread;
90 
91  public:
92  id() noexcept : _M_thread() { }
93 
94  explicit
95  id(native_handle_type __id) : _M_thread(__id) { }
96 
97  private:
98  friend class thread;
99  friend class hash<thread::id>;
100 
101  friend bool
102  operator==(thread::id __x, thread::id __y) noexcept;
103 
104  friend bool
105  operator<(thread::id __x, thread::id __y) noexcept;
106 
107  template<class _CharT, class _Traits>
108  friend basic_ostream<_CharT, _Traits>&
109  operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id);
110  };
111 
112  private:
113  id _M_id;
114 
115  // _GLIBCXX_RESOLVE_LIB_DEFECTS
116  // 2097. packaged_task constructors should be constrained
117  // 3039. Unnecessary decay in thread and packaged_task
118  template<typename _Tp>
119  using __not_same = __not_<is_same<__remove_cvref_t<_Tp>, thread>>;
120 
121  public:
122  thread() noexcept = default;
123 
124  template<typename _Callable, typename... _Args,
125  typename = _Require<__not_same<_Callable>>>
126  explicit
127  thread(_Callable&& __f, _Args&&... __args)
128  {
129  static_assert( __is_invocable<typename decay<_Callable>::type,
130  typename decay<_Args>::type...>::value,
131  "std::thread arguments must be invocable after conversion to rvalues"
132  );
133 
134 #ifdef GTHR_ACTIVE_PROXY
135  // Create a reference to pthread_create, not just the gthr weak symbol.
136  auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
137 #else
138  auto __depend = nullptr;
139 #endif
140  // A call wrapper holding tuple{DECAY_COPY(__f), DECAY_COPY(__args)...}
141  using _Invoker_type = _Invoker<__decayed_tuple<_Callable, _Args...>>;
142 
143  _M_start_thread(_S_make_state<_Invoker_type>(
144  std::forward<_Callable>(__f), std::forward<_Args>(__args)...),
145  __depend);
146  }
147 
148  ~thread()
149  {
150  if (joinable())
151  std::terminate();
152  }
153 
154  thread(const thread&) = delete;
155 
156  thread(thread&& __t) noexcept
157  { swap(__t); }
158 
159  thread& operator=(const thread&) = delete;
160 
161  thread& operator=(thread&& __t) noexcept
162  {
163  if (joinable())
164  std::terminate();
165  swap(__t);
166  return *this;
167  }
168 
169  void
170  swap(thread& __t) noexcept
171  { std::swap(_M_id, __t._M_id); }
172 
173  bool
174  joinable() const noexcept
175  { return !(_M_id == id()); }
176 
177  void
178  join();
179 
180  void
181  detach();
182 
183  thread::id
184  get_id() const noexcept
185  { return _M_id; }
186 
187  /** @pre thread is joinable
188  */
189  native_handle_type
190  native_handle()
191  { return _M_id._M_thread; }
192 
193  // Returns a value that hints at the number of hardware thread contexts.
194  static unsigned int
195  hardware_concurrency() noexcept;
196 
197  private:
198  template<typename _Callable>
199  struct _State_impl : public _State
200  {
201  _Callable _M_func;
202 
203  template<typename... _Args>
204  _State_impl(_Args&&... __args)
205  : _M_func{{std::forward<_Args>(__args)...}}
206  { }
207 
208  void
209  _M_run() { _M_func(); }
210  };
211 
212  void
213  _M_start_thread(_State_ptr, void (*)());
214 
215  template<typename _Callable, typename... _Args>
216  static _State_ptr
217  _S_make_state(_Args&&... __args)
218  {
219  using _Impl = _State_impl<_Callable>;
220  return _State_ptr{new _Impl{std::forward<_Args>(__args)...}};
221  }
222 #if _GLIBCXX_THREAD_ABI_COMPAT
223  public:
224  struct _Impl_base;
225  typedef shared_ptr<_Impl_base> __shared_base_type;
226  struct _Impl_base
227  {
228  __shared_base_type _M_this_ptr;
229  virtual ~_Impl_base() = default;
230  virtual void _M_run() = 0;
231  };
232 
233  private:
234  void
235  _M_start_thread(__shared_base_type, void (*)());
236 
237  void
238  _M_start_thread(__shared_base_type);
239 #endif
240 
241  private:
242  // A call wrapper that does INVOKE(forwarded tuple elements...)
243  template<typename _Tuple>
244  struct _Invoker
245  {
246  _Tuple _M_t;
247 
248  template<typename>
249  struct __result;
250  template<typename _Fn, typename... _Args>
251  struct __result<tuple<_Fn, _Args...>>
252  : __invoke_result<_Fn, _Args...>
253  { };
254 
255  template<size_t... _Ind>
256  typename __result<_Tuple>::type
257  _M_invoke(_Index_tuple<_Ind...>)
258  { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
259 
260  typename __result<_Tuple>::type
261  operator()()
262  {
263  using _Indices
264  = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
265  return _M_invoke(_Indices());
266  }
267  };
268 
269  template<typename... _Tp>
270  using __decayed_tuple = tuple<typename decay<_Tp>::type...>;
271 
272  public:
273  // Returns a call wrapper that stores
274  // tuple{DECAY_COPY(__callable), DECAY_COPY(__args)...}.
275  template<typename _Callable, typename... _Args>
276  static _Invoker<__decayed_tuple<_Callable, _Args...>>
277  __make_invoker(_Callable&& __callable, _Args&&... __args)
278  {
279  return { __decayed_tuple<_Callable, _Args...>{
280  std::forward<_Callable>(__callable), std::forward<_Args>(__args)...
281  } };
282  }
283  };
284 
285  inline void
286  swap(thread& __x, thread& __y) noexcept
287  { __x.swap(__y); }
288 
289  inline bool
290  operator==(thread::id __x, thread::id __y) noexcept
291  {
292  // pthread_equal is undefined if either thread ID is not valid, so we
293  // can't safely use __gthread_equal on default-constructed values (nor
294  // the non-zero value returned by this_thread::get_id() for
295  // single-threaded programs using GNU libc). Assume EqualityComparable.
296  return __x._M_thread == __y._M_thread;
297  }
298 
299  inline bool
300  operator!=(thread::id __x, thread::id __y) noexcept
301  { return !(__x == __y); }
302 
303  inline bool
304  operator<(thread::id __x, thread::id __y) noexcept
305  {
306  // Pthreads doesn't define any way to do this, so we just have to
307  // assume native_handle_type is LessThanComparable.
308  return __x._M_thread < __y._M_thread;
309  }
310 
311  inline bool
312  operator<=(thread::id __x, thread::id __y) noexcept
313  { return !(__y < __x); }
314 
315  inline bool
316  operator>(thread::id __x, thread::id __y) noexcept
317  { return __y < __x; }
318 
319  inline bool
320  operator>=(thread::id __x, thread::id __y) noexcept
321  { return !(__x < __y); }
322 
323  // DR 889.
324  /// std::hash specialization for thread::id.
325  template<>
326  struct hash<thread::id>
327  : public __hash_base<size_t, thread::id>
328  {
329  size_t
330  operator()(const thread::id& __id) const noexcept
331  { return std::_Hash_impl::hash(__id._M_thread); }
332  };
333 
334  template<class _CharT, class _Traits>
335  inline basic_ostream<_CharT, _Traits>&
336  operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
337  {
338  if (__id == thread::id())
339  return __out << "thread::id of a non-executing thread";
340  else
341  return __out << __id._M_thread;
342  }
343 
344  /** @namespace std::this_thread
345  * @brief ISO C++ 2011 namespace for interacting with the current thread
346  *
347  * C++11 30.3.2 [thread.thread.this] Namespace this_thread.
348  */
349  namespace this_thread
350  {
351  /// get_id
352  inline thread::id
353  get_id() noexcept
354  {
355 #ifdef __GLIBC__
356  // For the GNU C library pthread_self() is usable without linking to
357  // libpthread.so but returns 0, so we cannot use it in single-threaded
358  // programs, because this_thread::get_id() != thread::id{} must be true.
359  // We know that pthread_t is an integral type in the GNU C library.
360  if (!__gthread_active_p())
361  return thread::id(1);
362 #endif
363  return thread::id(__gthread_self());
364  }
365 
366  /// yield
367  inline void
368  yield() noexcept
369  {
370 #ifdef _GLIBCXX_USE_SCHED_YIELD
371  __gthread_yield();
372 #endif
373  }
374 
375  void
376  __sleep_for(chrono::seconds, chrono::nanoseconds);
377 
378  /// sleep_for
379  template<typename _Rep, typename _Period>
380  inline void
381  sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
382  {
383  if (__rtime <= __rtime.zero())
384  return;
385  auto __s = chrono::duration_cast<chrono::seconds>(__rtime);
386  auto __ns = chrono::duration_cast<chrono::nanoseconds>(__rtime - __s);
387 #ifdef _GLIBCXX_USE_NANOSLEEP
388  __gthread_time_t __ts =
389  {
390  static_cast<std::time_t>(__s.count()),
391  static_cast<long>(__ns.count())
392  };
393  while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
394  { }
395 #else
396  __sleep_for(__s, __ns);
397 #endif
398  }
399 
400  /// sleep_until
401  template<typename _Clock, typename _Duration>
402  inline void
403  sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)
404  {
405  auto __now = _Clock::now();
406  if (_Clock::is_steady)
407  {
408  if (__now < __atime)
409  sleep_for(__atime - __now);
410  return;
411  }
412  while (__now < __atime)
413  {
414  sleep_for(__atime - __now);
415  __now = _Clock::now();
416  }
417  }
418  }
419 
420  // @} group threads
421 
422 #ifdef __cpp_lib_jthread
423 
424  class jthread
425  {
426  public:
427  using id = std::thread::id;
428  using native_handle_type = std::thread::native_handle_type;
429 
430  jthread() noexcept
431  : _M_stop_source{nostopstate}
432  { }
433 
434  template<typename _Callable, typename... _Args,
435  typename = enable_if_t<!is_same_v<remove_cvref_t<_Callable>,
436  jthread>>>
437  explicit
438  jthread(_Callable&& __f, _Args&&... __args)
439  : _M_thread{_S_create(_M_stop_source, std::forward<_Callable>(__f),
440  std::forward<_Args>(__args)...)}
441  { }
442 
443  jthread(const jthread&) = delete;
444  jthread(jthread&&) noexcept = default;
445 
446  ~jthread()
447  {
448  if (joinable())
449  {
450  request_stop();
451  join();
452  }
453  }
454 
455  jthread&
456  operator=(const jthread&) = delete;
457 
458  jthread&
459  operator=(jthread&&) noexcept = default;
460 
461  void
462  swap(jthread& __other) noexcept
463  {
464  std::swap(_M_stop_source, __other._M_stop_source);
465  std::swap(_M_thread, __other._M_thread);
466  }
467 
468  [[nodiscard]] bool
469  joinable() const noexcept
470  {
471  return _M_thread.joinable();
472  }
473 
474  void
475  join()
476  {
477  _M_thread.join();
478  }
479 
480  void
481  detach()
482  {
483  _M_thread.detach();
484  }
485 
486  [[nodiscard]] id
487  get_id() const noexcept
488  {
489  return _M_thread.get_id();
490  }
491 
492  [[nodiscard]] native_handle_type
493  native_handle()
494  {
495  return _M_thread.native_handle();
496  }
497 
498  [[nodiscard]] static unsigned
499  hardware_concurrency() noexcept
500  {
501  return std::thread::hardware_concurrency();
502  }
503 
504  [[nodiscard]] stop_source
505  get_stop_source() noexcept
506  {
507  return _M_stop_source;
508  }
509 
510  [[nodiscard]] stop_token
511  get_stop_token() const noexcept
512  {
513  return _M_stop_source.get_token();
514  }
515 
516  bool request_stop() noexcept
517  {
518  return _M_stop_source.request_stop();
519  }
520 
521  friend void swap(jthread& __lhs, jthread& __rhs) noexcept
522  {
523  __lhs.swap(__rhs);
524  }
525 
526  private:
527  template<typename _Callable, typename... _Args>
528  static thread
529  _S_create(stop_source& __ssrc, _Callable&& __f, _Args&&... __args)
530  {
531  if constexpr(is_invocable_v<decay_t<_Callable>, stop_token,
532  decay_t<_Args>...>)
533  return thread{std::forward<_Callable>(__f), __ssrc.get_token(),
534  std::forward<_Args>(__args)...};
535  else
536  {
537  static_assert(is_invocable_v<decay_t<_Callable>,
538  decay_t<_Args>...>,
539  "std::thread arguments must be invocable after"
540  " conversion to rvalues");
541  return thread{std::forward<_Callable>(__f),
542  std::forward<_Args>(__args)...};
543  }
544  }
545 
546  stop_source _M_stop_source;
547  std::thread _M_thread;
548  };
549 #endif // __cpp_lib_jthread
550 _GLIBCXX_END_NAMESPACE_VERSION
551 } // namespace
552 #endif // _GLIBCXX_HAS_GTHREADS
553 #endif // C++11
554 #endif // _GLIBCXX_THREAD
std::unique_ptr
20.7.1.2 unique_ptr for single objects.
Definition: unique_ptr.h:238
std::thread
thread
Definition: thread:72
std
ISO C++ entities toplevel namespace is std.
memory
c++config.h
std::thread::id
thread::id
Definition: thread:87
stop_token
chrono
std::hash
Primary class template hash.
Definition: typeindex:93
tuple
c++0x_warning.h
functional_hash.h
cerrno
invoke.h