std_thread.h 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. // std::thread declarations -*- C++ -*-
  2. // Copyright (C) 2008-2021 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 <exception> // std::terminate
  30. #include <iosfwd> // std::basic_ostream
  31. #include <tuple> // std::tuple
  32. #include <bits/functional_hash.h> // std::hash
  33. #include <bits/invoke.h> // std::__invoke
  34. #include <bits/refwrap.h> // not required, but helpful to users
  35. #include <bits/unique_ptr.h> // std::unique_ptr
  36. #ifdef _GLIBCXX_HAS_GTHREADS
  37. # include <bits/gthr.h>
  38. #else
  39. # include <errno.h>
  40. # include <bits/functexcept.h>
  41. #endif
  42. namespace std _GLIBCXX_VISIBILITY(default)
  43. {
  44. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  45. /** @addtogroup threads
  46. * @{
  47. */
  48. /// thread
  49. class thread
  50. {
  51. public:
  52. #ifdef _GLIBCXX_HAS_GTHREADS
  53. // Abstract base class for types that wrap arbitrary functors to be
  54. // invoked in the new thread of execution.
  55. struct _State
  56. {
  57. virtual ~_State();
  58. virtual void _M_run() = 0;
  59. };
  60. using _State_ptr = unique_ptr<_State>;
  61. using native_handle_type = __gthread_t;
  62. #else
  63. using native_handle_type = int;
  64. #endif
  65. /// thread::id
  66. class id
  67. {
  68. native_handle_type _M_thread;
  69. public:
  70. id() noexcept : _M_thread() { }
  71. explicit
  72. id(native_handle_type __id) : _M_thread(__id) { }
  73. private:
  74. friend class thread;
  75. friend struct hash<id>;
  76. friend bool
  77. operator==(id __x, id __y) noexcept;
  78. #if __cpp_lib_three_way_comparison
  79. friend strong_ordering
  80. operator<=>(id __x, id __y) noexcept;
  81. #else
  82. friend bool
  83. operator<(id __x, id __y) noexcept;
  84. #endif
  85. template<class _CharT, class _Traits>
  86. friend basic_ostream<_CharT, _Traits>&
  87. operator<<(basic_ostream<_CharT, _Traits>& __out, id __id);
  88. };
  89. private:
  90. id _M_id;
  91. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  92. // 2097. packaged_task constructors should be constrained
  93. // 3039. Unnecessary decay in thread and packaged_task
  94. template<typename _Tp>
  95. using __not_same = __not_<is_same<__remove_cvref_t<_Tp>, thread>>;
  96. public:
  97. thread() noexcept = default;
  98. #ifdef _GLIBCXX_HAS_GTHREADS
  99. template<typename _Callable, typename... _Args,
  100. typename = _Require<__not_same<_Callable>>>
  101. explicit
  102. thread(_Callable&& __f, _Args&&... __args)
  103. {
  104. static_assert( __is_invocable<typename decay<_Callable>::type,
  105. typename decay<_Args>::type...>::value,
  106. "std::thread arguments must be invocable after conversion to rvalues"
  107. );
  108. #ifdef GTHR_ACTIVE_PROXY
  109. // Create a reference to pthread_create, not just the gthr weak symbol.
  110. auto __depend = reinterpret_cast<void(*)()>(&pthread_create);
  111. #else
  112. auto __depend = nullptr;
  113. #endif
  114. using _Wrapper = _Call_wrapper<_Callable, _Args...>;
  115. // Create a call wrapper with DECAY_COPY(__f) as its target object
  116. // and DECAY_COPY(__args)... as its bound argument entities.
  117. _M_start_thread(_State_ptr(new _State_impl<_Wrapper>(
  118. std::forward<_Callable>(__f), std::forward<_Args>(__args)...)),
  119. __depend);
  120. }
  121. #endif // _GLIBCXX_HAS_GTHREADS
  122. ~thread()
  123. {
  124. if (joinable())
  125. std::terminate();
  126. }
  127. thread(const thread&) = delete;
  128. thread(thread&& __t) noexcept
  129. { swap(__t); }
  130. thread& operator=(const thread&) = delete;
  131. thread& operator=(thread&& __t) noexcept
  132. {
  133. if (joinable())
  134. std::terminate();
  135. swap(__t);
  136. return *this;
  137. }
  138. void
  139. swap(thread& __t) noexcept
  140. { std::swap(_M_id, __t._M_id); }
  141. bool
  142. joinable() const noexcept
  143. { return !(_M_id == id()); }
  144. void
  145. join();
  146. void
  147. detach();
  148. id
  149. get_id() const noexcept
  150. { return _M_id; }
  151. /** @pre thread is joinable
  152. */
  153. native_handle_type
  154. native_handle()
  155. { return _M_id._M_thread; }
  156. // Returns a value that hints at the number of hardware thread contexts.
  157. static unsigned int
  158. hardware_concurrency() noexcept;
  159. #ifdef _GLIBCXX_HAS_GTHREADS
  160. private:
  161. template<typename _Callable>
  162. struct _State_impl : public _State
  163. {
  164. _Callable _M_func;
  165. template<typename... _Args>
  166. _State_impl(_Args&&... __args)
  167. : _M_func{{std::forward<_Args>(__args)...}}
  168. { }
  169. void
  170. _M_run() { _M_func(); }
  171. };
  172. void
  173. _M_start_thread(_State_ptr, void (*)());
  174. #if _GLIBCXX_THREAD_ABI_COMPAT
  175. public:
  176. struct _Impl_base;
  177. typedef shared_ptr<_Impl_base> __shared_base_type;
  178. struct _Impl_base
  179. {
  180. __shared_base_type _M_this_ptr;
  181. virtual ~_Impl_base() = default;
  182. virtual void _M_run() = 0;
  183. };
  184. private:
  185. void
  186. _M_start_thread(__shared_base_type, void (*)());
  187. void
  188. _M_start_thread(__shared_base_type);
  189. #endif
  190. private:
  191. // A call wrapper that does INVOKE(forwarded tuple elements...)
  192. template<typename _Tuple>
  193. struct _Invoker
  194. {
  195. _Tuple _M_t;
  196. template<typename>
  197. struct __result;
  198. template<typename _Fn, typename... _Args>
  199. struct __result<tuple<_Fn, _Args...>>
  200. : __invoke_result<_Fn, _Args...>
  201. { };
  202. template<size_t... _Ind>
  203. typename __result<_Tuple>::type
  204. _M_invoke(_Index_tuple<_Ind...>)
  205. { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
  206. typename __result<_Tuple>::type
  207. operator()()
  208. {
  209. using _Indices
  210. = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
  211. return _M_invoke(_Indices());
  212. }
  213. };
  214. public:
  215. template<typename... _Tp>
  216. using _Call_wrapper = _Invoker<tuple<typename decay<_Tp>::type...>>;
  217. #endif // _GLIBCXX_HAS_GTHREADS
  218. };
  219. #ifndef _GLIBCXX_HAS_GTHREADS
  220. inline void thread::join() { std::__throw_system_error(EINVAL); }
  221. inline void thread::detach() { std::__throw_system_error(EINVAL); }
  222. inline unsigned int thread::hardware_concurrency() { return 0; }
  223. #endif
  224. inline void
  225. swap(thread& __x, thread& __y) noexcept
  226. { __x.swap(__y); }
  227. inline bool
  228. operator==(thread::id __x, thread::id __y) noexcept
  229. {
  230. // pthread_equal is undefined if either thread ID is not valid, so we
  231. // can't safely use __gthread_equal on default-constructed values (nor
  232. // the non-zero value returned by this_thread::get_id() for
  233. // single-threaded programs using GNU libc). Assume EqualityComparable.
  234. return __x._M_thread == __y._M_thread;
  235. }
  236. // N.B. other comparison operators are defined in <thread>
  237. // DR 889.
  238. /// std::hash specialization for thread::id.
  239. template<>
  240. struct hash<thread::id>
  241. : public __hash_base<size_t, thread::id>
  242. {
  243. size_t
  244. operator()(const thread::id& __id) const noexcept
  245. { return std::_Hash_impl::hash(__id._M_thread); }
  246. };
  247. namespace this_thread
  248. {
  249. /// this_thread::get_id
  250. inline thread::id
  251. get_id() noexcept
  252. {
  253. #ifndef _GLIBCXX_HAS_GTHREADS
  254. return thread::id(1);
  255. #elif defined _GLIBCXX_NATIVE_THREAD_ID
  256. return thread::id(_GLIBCXX_NATIVE_THREAD_ID);
  257. #else
  258. return thread::id(__gthread_self());
  259. #endif
  260. }
  261. /// this_thread::yield
  262. inline void
  263. yield() noexcept
  264. {
  265. #if defined _GLIBCXX_HAS_GTHREADS && defined _GLIBCXX_USE_SCHED_YIELD
  266. __gthread_yield();
  267. #endif
  268. }
  269. } // namespace this_thread
  270. /// @}
  271. _GLIBCXX_END_NAMESPACE_VERSION
  272. } // namespace
  273. #endif // C++11
  274. #endif // _GLIBCXX_THREAD_H