std_thread.h 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. // std::thread declarations -*- C++ -*-
  2. // Copyright (C) 2008-2022 Free Software Foundation, Inc.
  3. //
  4. // This file is part of the GNU ISO C++ Library. This library is free
  5. // software; you can redistribute it and/or modify it under the
  6. // terms of the GNU General Public License as published by the
  7. // Free Software Foundation; either version 3, or (at your option)
  8. // any later version.
  9. // This library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. // Under Section 7 of GPL version 3, you are granted additional
  14. // permissions described in the GCC Runtime Library Exception, version
  15. // 3.1, as published by the Free Software Foundation.
  16. // You should have received a copy of the GNU General Public License and
  17. // a copy of the GCC Runtime Library Exception along with this program;
  18. // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. // <http://www.gnu.org/licenses/>.
  20. /** @file bits/std_thread.h
  21. * This is an internal header file, included by other library headers.
  22. * Do not attempt to use it directly. @headername{thread}
  23. */
  24. #ifndef _GLIBCXX_THREAD_H
  25. #define _GLIBCXX_THREAD_H 1
  26. #pragma GCC system_header
  27. #if __cplusplus >= 201103L
  28. #include <bits/c++config.h>
  29. #include <iosfwd> // std::basic_ostream
  30. #include <tuple> // std::tuple
  31. #include <bits/functional_hash.h> // std::hash
  32. #include <bits/invoke.h> // std::__invoke
  33. #include <bits/refwrap.h> // not required, but helpful to users
  34. #include <bits/unique_ptr.h> // std::unique_ptr
  35. #ifdef _GLIBCXX_HAS_GTHREADS
  36. # include <bits/gthr.h>
  37. #else
  38. # include <errno.h>
  39. # include <bits/functexcept.h>
  40. #endif
  41. namespace std _GLIBCXX_VISIBILITY(default)
  42. {
  43. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  44. /** @addtogroup threads
  45. * @{
  46. */
  47. /// thread
  48. class thread
  49. {
  50. public:
  51. #ifdef _GLIBCXX_HAS_GTHREADS
  52. // Abstract base class for types that wrap arbitrary functors to be
  53. // invoked in the new thread of execution.
  54. struct _State
  55. {
  56. virtual ~_State();
  57. virtual void _M_run() = 0;
  58. };
  59. using _State_ptr = unique_ptr<_State>;
  60. using native_handle_type = __gthread_t;
  61. #else
  62. using native_handle_type = int;
  63. #endif
  64. /// thread::id
  65. class id
  66. {
  67. native_handle_type _M_thread;
  68. public:
  69. id() noexcept : _M_thread() { }
  70. explicit
  71. id(native_handle_type __id) : _M_thread(__id) { }
  72. private:
  73. friend class thread;
  74. friend struct hash<id>;
  75. friend bool
  76. operator==(id __x, id __y) noexcept;
  77. #if __cpp_lib_three_way_comparison
  78. friend strong_ordering
  79. operator<=>(id __x, id __y) noexcept;
  80. #else
  81. friend bool
  82. operator<(id __x, id __y) noexcept;
  83. #endif
  84. template<class _CharT, class _Traits>
  85. friend basic_ostream<_CharT, _Traits>&
  86. operator<<(basic_ostream<_CharT, _Traits>& __out, id __id);
  87. };
  88. private:
  89. id _M_id;
  90. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  91. // 2097. packaged_task constructors should be constrained
  92. // 3039. Unnecessary decay in thread and packaged_task
  93. template<typename _Tp>
  94. using __not_same = __not_<is_same<__remove_cvref_t<_Tp>, thread>>;
  95. public:
  96. thread() noexcept = default;
  97. #ifdef _GLIBCXX_HAS_GTHREADS
  98. template<typename _Callable, typename... _Args,
  99. typename = _Require<__not_same<_Callable>>>
  100. explicit
  101. thread(_Callable&& __f, _Args&&... __args)
  102. {
  103. static_assert( __is_invocable<typename decay<_Callable>::type,
  104. typename decay<_Args>::type...>::value,
  105. "std::thread arguments must be invocable after conversion to rvalues"
  106. );
  107. #ifdef GTHR_ACTIVE_PROXY
  108. // Create a reference to pthread_create, not just the gthr weak symbol.
  109. auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
  110. #else
  111. auto __depend = nullptr;
  112. #endif
  113. using _Wrapper = _Call_wrapper<_Callable, _Args...>;
  114. // Create a call wrapper with DECAY_COPY(__f) as its target object
  115. // and DECAY_COPY(__args)... as its bound argument entities.
  116. _M_start_thread(_State_ptr(new _State_impl<_Wrapper>(
  117. std::forward<_Callable>(__f), std::forward<_Args>(__args)...)),
  118. __depend);
  119. }
  120. #endif // _GLIBCXX_HAS_GTHREADS
  121. ~thread()
  122. {
  123. if (joinable())
  124. std::__terminate();
  125. }
  126. thread(const thread&) = delete;
  127. thread(thread&& __t) noexcept
  128. { swap(__t); }
  129. thread& operator=(const thread&) = delete;
  130. thread& operator=(thread&& __t) noexcept
  131. {
  132. if (joinable())
  133. std::__terminate();
  134. swap(__t);
  135. return *this;
  136. }
  137. void
  138. swap(thread& __t) noexcept
  139. { std::swap(_M_id, __t._M_id); }
  140. bool
  141. joinable() const noexcept
  142. { return !(_M_id == id()); }
  143. void
  144. join();
  145. void
  146. detach();
  147. id
  148. get_id() const noexcept
  149. { return _M_id; }
  150. /** @pre thread is joinable
  151. */
  152. native_handle_type
  153. native_handle()
  154. { return _M_id._M_thread; }
  155. // Returns a value that hints at the number of hardware thread contexts.
  156. static unsigned int
  157. hardware_concurrency() noexcept;
  158. #ifdef _GLIBCXX_HAS_GTHREADS
  159. private:
  160. template<typename _Callable>
  161. struct _State_impl : public _State
  162. {
  163. _Callable _M_func;
  164. template<typename... _Args>
  165. _State_impl(_Args&&... __args)
  166. : _M_func{{std::forward<_Args>(__args)...}}
  167. { }
  168. void
  169. _M_run() { _M_func(); }
  170. };
  171. void
  172. _M_start_thread(_State_ptr, void (*)());
  173. #if _GLIBCXX_THREAD_ABI_COMPAT
  174. public:
  175. struct _Impl_base;
  176. typedef shared_ptr<_Impl_base> __shared_base_type;
  177. struct _Impl_base
  178. {
  179. __shared_base_type _M_this_ptr;
  180. virtual ~_Impl_base() = default;
  181. virtual void _M_run() = 0;
  182. };
  183. private:
  184. void
  185. _M_start_thread(__shared_base_type, void (*)());
  186. void
  187. _M_start_thread(__shared_base_type);
  188. #endif
  189. private:
  190. // A call wrapper that does INVOKE(forwarded tuple elements...)
  191. template<typename _Tuple>
  192. struct _Invoker
  193. {
  194. _Tuple _M_t;
  195. template<typename>
  196. struct __result;
  197. template<typename _Fn, typename... _Args>
  198. struct __result<tuple<_Fn, _Args...>>
  199. : __invoke_result<_Fn, _Args...>
  200. { };
  201. template<size_t... _Ind>
  202. typename __result<_Tuple>::type
  203. _M_invoke(_Index_tuple<_Ind...>)
  204. { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
  205. typename __result<_Tuple>::type
  206. operator()()
  207. {
  208. using _Indices
  209. = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
  210. return _M_invoke(_Indices());
  211. }
  212. };
  213. public:
  214. template<typename... _Tp>
  215. using _Call_wrapper = _Invoker<tuple<typename decay<_Tp>::type...>>;
  216. #endif // _GLIBCXX_HAS_GTHREADS
  217. };
  218. #ifndef _GLIBCXX_HAS_GTHREADS
  219. inline void thread::join() { std::__throw_system_error(EINVAL); }
  220. inline void thread::detach() { std::__throw_system_error(EINVAL); }
  221. inline unsigned int thread::hardware_concurrency() noexcept { return 0; }
  222. #endif
  223. inline void
  224. swap(thread& __x, thread& __y) noexcept
  225. { __x.swap(__y); }
  226. inline bool
  227. operator==(thread::id __x, thread::id __y) noexcept
  228. {
  229. // pthread_equal is undefined if either thread ID is not valid, so we
  230. // can't safely use __gthread_equal on default-constructed values (nor
  231. // the non-zero value returned by this_thread::get_id() for
  232. // single-threaded programs using GNU libc). Assume EqualityComparable.
  233. return __x._M_thread == __y._M_thread;
  234. }
  235. // N.B. other comparison operators are defined in <thread>
  236. // DR 889.
  237. /// std::hash specialization for thread::id.
  238. template<>
  239. struct hash<thread::id>
  240. : public __hash_base<size_t, thread::id>
  241. {
  242. size_t
  243. operator()(const thread::id& __id) const noexcept
  244. { return std::_Hash_impl::hash(__id._M_thread); }
  245. };
  246. namespace this_thread
  247. {
  248. /// this_thread::get_id
  249. inline thread::id
  250. get_id() noexcept
  251. {
  252. #ifndef _GLIBCXX_HAS_GTHREADS
  253. return thread::id(1);
  254. #elif defined _GLIBCXX_NATIVE_THREAD_ID
  255. return thread::id(_GLIBCXX_NATIVE_THREAD_ID);
  256. #else
  257. return thread::id(__gthread_self());
  258. #endif
  259. }
  260. /// this_thread::yield
  261. inline void
  262. yield() noexcept
  263. {
  264. #if defined _GLIBCXX_HAS_GTHREADS && defined _GLIBCXX_USE_SCHED_YIELD
  265. __gthread_yield();
  266. #endif
  267. }
  268. } // namespace this_thread
  269. /// @}
  270. _GLIBCXX_END_NAMESPACE_VERSION
  271. } // namespace
  272. #endif // C++11
  273. #endif // _GLIBCXX_THREAD_H