std_thread.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. // std::thread declarations -*- C++ -*-
  2. // Copyright (C) 2008-2023 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. /** A std::thread represents a new thread of execution.
  48. *
  49. * The default constructor creates an object that does not own a thread.
  50. * The `thread(F&&, Args&&...)` constructor invokes a callable in a new
  51. * thread, and owns that new thread. A `std::thread` that owns a thread
  52. * is *joinable*. Joining a thread waits for it to finish executing,
  53. * which happens when the callable running in that thread returns.
  54. *
  55. * A `std::thread` cannot be copied, but can be moved. Moving a joinable
  56. * object transfers ownership of its thread to another object.
  57. *
  58. * A joinable `std::thread` must be explicitly joined (or detached) before
  59. * it is destroyed or assigned to. Attempting to destroy a joinable thread
  60. * will terminate the whole process.
  61. *
  62. * @headerfile thread
  63. * @since C++11
  64. */
  65. class thread
  66. {
  67. public:
  68. #ifdef _GLIBCXX_HAS_GTHREADS
  69. using native_handle_type = __gthread_t;
  70. #else
  71. using native_handle_type = int;
  72. #endif
  73. /** A std::thread::id is a unique identifier for a thread.
  74. *
  75. * @headerfile thread
  76. * @since C++11
  77. */
  78. class id
  79. {
  80. native_handle_type _M_thread;
  81. public:
  82. id() noexcept : _M_thread() { }
  83. explicit
  84. id(native_handle_type __id) : _M_thread(__id) { }
  85. private:
  86. friend class thread;
  87. friend struct hash<id>;
  88. friend bool
  89. operator==(id __x, id __y) noexcept;
  90. #if __cpp_lib_three_way_comparison
  91. friend strong_ordering
  92. operator<=>(id __x, id __y) noexcept;
  93. #else
  94. friend bool
  95. operator<(id __x, id __y) noexcept;
  96. #endif
  97. template<class _CharT, class _Traits>
  98. friend basic_ostream<_CharT, _Traits>&
  99. operator<<(basic_ostream<_CharT, _Traits>& __out, id __id);
  100. };
  101. private:
  102. id _M_id;
  103. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  104. // 2097. packaged_task constructors should be constrained
  105. // 3039. Unnecessary decay in thread and packaged_task
  106. template<typename _Tp>
  107. using __not_same = __not_<is_same<__remove_cvref_t<_Tp>, thread>>;
  108. public:
  109. thread() noexcept = default;
  110. #ifdef _GLIBCXX_HAS_GTHREADS
  111. private:
  112. // This adds to user code that creates std:thread objects (because
  113. // it is called by the template ctor below) strong references to
  114. // pthread_create and pthread_join, which ensures they are both
  115. // linked in even during static linking. We can't depend on
  116. // gthread calls to bring them in, because those may use weak
  117. // references.
  118. static void
  119. _M_thread_deps_never_run() {
  120. #ifdef GTHR_ACTIVE_PROXY
  121. reinterpret_cast<void (*)(void)>(&pthread_create)();
  122. reinterpret_cast<void (*)(void)>(&pthread_join)();
  123. #endif
  124. }
  125. public:
  126. template<typename _Callable, typename... _Args,
  127. typename = _Require<__not_same<_Callable>>>
  128. explicit
  129. thread(_Callable&& __f, _Args&&... __args)
  130. {
  131. static_assert( __is_invocable<typename decay<_Callable>::type,
  132. typename decay<_Args>::type...>::value,
  133. "std::thread arguments must be invocable after conversion to rvalues"
  134. );
  135. using _Wrapper = _Call_wrapper<_Callable, _Args...>;
  136. // Create a call wrapper with DECAY_COPY(__f) as its target object
  137. // and DECAY_COPY(__args)... as its bound argument entities.
  138. _M_start_thread(_State_ptr(new _State_impl<_Wrapper>(
  139. std::forward<_Callable>(__f), std::forward<_Args>(__args)...)),
  140. _M_thread_deps_never_run);
  141. }
  142. #endif // _GLIBCXX_HAS_GTHREADS
  143. ~thread()
  144. {
  145. if (joinable())
  146. std::__terminate();
  147. }
  148. thread(const thread&) = delete;
  149. thread(thread&& __t) noexcept
  150. { swap(__t); }
  151. thread& operator=(const thread&) = delete;
  152. thread& operator=(thread&& __t) noexcept
  153. {
  154. if (joinable())
  155. std::__terminate();
  156. swap(__t);
  157. return *this;
  158. }
  159. void
  160. swap(thread& __t) noexcept
  161. { std::swap(_M_id, __t._M_id); }
  162. bool
  163. joinable() const noexcept
  164. { return !(_M_id == id()); }
  165. void
  166. join();
  167. void
  168. detach();
  169. id
  170. get_id() const noexcept
  171. { return _M_id; }
  172. /** @pre thread is joinable
  173. */
  174. native_handle_type
  175. native_handle()
  176. { return _M_id._M_thread; }
  177. // Returns a value that hints at the number of hardware thread contexts.
  178. static unsigned int
  179. hardware_concurrency() noexcept;
  180. #ifdef _GLIBCXX_HAS_GTHREADS
  181. #ifndef _GLIBCXX_THREAD_IMPL
  182. private:
  183. #endif
  184. // Abstract base class for types that wrap arbitrary functors to be
  185. // invoked in the new thread of execution.
  186. struct _State
  187. {
  188. virtual ~_State();
  189. virtual void _M_run() = 0;
  190. };
  191. using _State_ptr = unique_ptr<_State>;
  192. private:
  193. template<typename _Callable>
  194. struct _State_impl : public _State
  195. {
  196. _Callable _M_func;
  197. template<typename... _Args>
  198. _State_impl(_Args&&... __args)
  199. : _M_func(std::forward<_Args>(__args)...)
  200. { }
  201. void
  202. _M_run() { _M_func(); }
  203. };
  204. void
  205. _M_start_thread(_State_ptr, void (*)());
  206. #if _GLIBCXX_THREAD_ABI_COMPAT
  207. public:
  208. struct _Impl_base;
  209. typedef shared_ptr<_Impl_base> __shared_base_type;
  210. struct _Impl_base
  211. {
  212. __shared_base_type _M_this_ptr;
  213. virtual ~_Impl_base() = default;
  214. virtual void _M_run() = 0;
  215. };
  216. private:
  217. void
  218. _M_start_thread(__shared_base_type, void (*)());
  219. void
  220. _M_start_thread(__shared_base_type);
  221. #endif
  222. private:
  223. // A call wrapper that does INVOKE(forwarded tuple elements...)
  224. template<typename _Tuple>
  225. struct _Invoker
  226. {
  227. template<typename... _Args>
  228. explicit
  229. _Invoker(_Args&&... __args)
  230. : _M_t(std::forward<_Args>(__args)...)
  231. { }
  232. _Tuple _M_t;
  233. template<typename>
  234. struct __result;
  235. template<typename _Fn, typename... _Args>
  236. struct __result<tuple<_Fn, _Args...>>
  237. : __invoke_result<_Fn, _Args...>
  238. { };
  239. template<size_t... _Ind>
  240. typename __result<_Tuple>::type
  241. _M_invoke(_Index_tuple<_Ind...>)
  242. { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }
  243. typename __result<_Tuple>::type
  244. operator()()
  245. {
  246. using _Indices
  247. = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;
  248. return _M_invoke(_Indices());
  249. }
  250. };
  251. public:
  252. /// @cond undocumented
  253. template<typename... _Tp>
  254. using _Call_wrapper = _Invoker<tuple<typename decay<_Tp>::type...>>;
  255. /// @endcond
  256. #endif // _GLIBCXX_HAS_GTHREADS
  257. };
  258. #ifndef _GLIBCXX_HAS_GTHREADS
  259. inline void thread::join() { std::__throw_system_error(EINVAL); }
  260. inline void thread::detach() { std::__throw_system_error(EINVAL); }
  261. inline unsigned int thread::hardware_concurrency() noexcept { return 0; }
  262. #endif
  263. /// @relates std::thread
  264. inline void
  265. swap(thread& __x, thread& __y) noexcept
  266. { __x.swap(__y); }
  267. /// @relates std::thread::id
  268. inline bool
  269. operator==(thread::id __x, thread::id __y) noexcept
  270. {
  271. // pthread_equal is undefined if either thread ID is not valid, so we
  272. // can't safely use __gthread_equal on default-constructed values (nor
  273. // the non-zero value returned by this_thread::get_id() for
  274. // single-threaded programs using GNU libc). Assume EqualityComparable.
  275. return __x._M_thread == __y._M_thread;
  276. }
  277. // N.B. other comparison operators are defined in <thread>
  278. // DR 889.
  279. /// std::hash specialization for thread::id.
  280. template<>
  281. struct hash<thread::id>
  282. : public __hash_base<size_t, thread::id>
  283. {
  284. size_t
  285. operator()(const thread::id& __id) const noexcept
  286. { return std::_Hash_impl::hash(__id._M_thread); }
  287. };
  288. namespace this_thread
  289. {
  290. /// The unique identifier of the current thread.
  291. inline thread::id
  292. get_id() noexcept
  293. {
  294. #ifndef _GLIBCXX_HAS_GTHREADS
  295. return thread::id(1);
  296. #elif defined _GLIBCXX_NATIVE_THREAD_ID
  297. return thread::id(_GLIBCXX_NATIVE_THREAD_ID);
  298. #else
  299. return thread::id(__gthread_self());
  300. #endif
  301. }
  302. /// Allow the implementation to schedule a different thread.
  303. inline void
  304. yield() noexcept
  305. {
  306. #if defined _GLIBCXX_HAS_GTHREADS && defined _GLIBCXX_USE_SCHED_YIELD
  307. __gthread_yield();
  308. #endif
  309. }
  310. } // namespace this_thread
  311. /// @}
  312. _GLIBCXX_END_NAMESPACE_VERSION
  313. } // namespace
  314. #endif // C++11
  315. #endif // _GLIBCXX_THREAD_H