thread 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // -*- C++ -*-
  2. //===----------------------------------------------------------------------===//
  3. //
  4. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  5. // See https://llvm.org/LICENSE.txt for license information.
  6. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #ifndef _LIBCPP_THREAD
  10. #define _LIBCPP_THREAD
  11. /*
  12. thread synopsis
  13. namespace std
  14. {
  15. class thread
  16. {
  17. public:
  18. class id;
  19. typedef pthread_t native_handle_type;
  20. thread() noexcept;
  21. template <class F, class ...Args> explicit thread(F&& f, Args&&... args);
  22. ~thread();
  23. thread(const thread&) = delete;
  24. thread(thread&& t) noexcept;
  25. thread& operator=(const thread&) = delete;
  26. thread& operator=(thread&& t) noexcept;
  27. void swap(thread& t) noexcept;
  28. bool joinable() const noexcept;
  29. void join();
  30. void detach();
  31. id get_id() const noexcept;
  32. native_handle_type native_handle();
  33. static unsigned hardware_concurrency() noexcept;
  34. };
  35. void swap(thread& x, thread& y) noexcept;
  36. class thread::id
  37. {
  38. public:
  39. id() noexcept;
  40. };
  41. bool operator==(thread::id x, thread::id y) noexcept;
  42. bool operator!=(thread::id x, thread::id y) noexcept; // removed in C++20
  43. bool operator< (thread::id x, thread::id y) noexcept; // removed in C++20
  44. bool operator<=(thread::id x, thread::id y) noexcept; // removed in C++20
  45. bool operator> (thread::id x, thread::id y) noexcept; // removed in C++20
  46. bool operator>=(thread::id x, thread::id y) noexcept; // removed in C++20
  47. strong_ordering operator<=>(thread::id x, thread::id y) noexcept; // C++20
  48. template<class charT, class traits>
  49. basic_ostream<charT, traits>&
  50. operator<<(basic_ostream<charT, traits>& out, thread::id id);
  51. namespace this_thread
  52. {
  53. thread::id get_id() noexcept;
  54. void yield() noexcept;
  55. template <class Clock, class Duration>
  56. void sleep_until(const chrono::time_point<Clock, Duration>& abs_time);
  57. template <class Rep, class Period>
  58. void sleep_for(const chrono::duration<Rep, Period>& rel_time);
  59. } // this_thread
  60. } // std
  61. */
  62. #include <__assert> // all public C++ headers provide the assertion handler
  63. #include <__config>
  64. #include <__functional/hash.h>
  65. #include <__memory/unique_ptr.h>
  66. #include <__mutex_base>
  67. #include <__thread/poll_with_backoff.h>
  68. #include <__thread/timed_backoff_policy.h>
  69. #include <__threading_support>
  70. #include <__utility/forward.h>
  71. #include <cstddef>
  72. #include <iosfwd>
  73. #include <system_error>
  74. #include <tuple>
  75. #include <type_traits>
  76. #include <version>
  77. // standard-mandated includes
  78. // [thread.syn]
  79. #include <compare>
  80. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  81. # pragma GCC system_header
  82. #endif
  83. _LIBCPP_PUSH_MACROS
  84. #include <__undef_macros>
  85. #ifdef _LIBCPP_HAS_NO_THREADS
  86. # error "<thread> is not supported since libc++ has been configured without support for threads."
  87. #endif
  88. _LIBCPP_BEGIN_NAMESPACE_STD
  89. template <class _Tp> class __thread_specific_ptr;
  90. class _LIBCPP_TYPE_VIS __thread_struct;
  91. class _LIBCPP_HIDDEN __thread_struct_imp;
  92. class __assoc_sub_state;
  93. _LIBCPP_FUNC_VIS __thread_specific_ptr<__thread_struct>& __thread_local_data();
  94. class _LIBCPP_TYPE_VIS __thread_struct
  95. {
  96. __thread_struct_imp* __p_;
  97. __thread_struct(const __thread_struct&);
  98. __thread_struct& operator=(const __thread_struct&);
  99. public:
  100. __thread_struct();
  101. ~__thread_struct();
  102. void notify_all_at_thread_exit(condition_variable*, mutex*);
  103. void __make_ready_at_thread_exit(__assoc_sub_state*);
  104. };
  105. template <class _Tp>
  106. class __thread_specific_ptr
  107. {
  108. __libcpp_tls_key __key_;
  109. // Only __thread_local_data() may construct a __thread_specific_ptr
  110. // and only with _Tp == __thread_struct.
  111. static_assert((is_same<_Tp, __thread_struct>::value), "");
  112. __thread_specific_ptr();
  113. friend _LIBCPP_FUNC_VIS __thread_specific_ptr<__thread_struct>& __thread_local_data();
  114. __thread_specific_ptr(const __thread_specific_ptr&);
  115. __thread_specific_ptr& operator=(const __thread_specific_ptr&);
  116. _LIBCPP_HIDDEN static void _LIBCPP_TLS_DESTRUCTOR_CC __at_thread_exit(void*);
  117. public:
  118. typedef _Tp* pointer;
  119. ~__thread_specific_ptr();
  120. _LIBCPP_INLINE_VISIBILITY
  121. pointer get() const {return static_cast<_Tp*>(__libcpp_tls_get(__key_));}
  122. _LIBCPP_INLINE_VISIBILITY
  123. pointer operator*() const {return *get();}
  124. _LIBCPP_INLINE_VISIBILITY
  125. pointer operator->() const {return get();}
  126. void set_pointer(pointer __p);
  127. };
  128. template <class _Tp>
  129. void _LIBCPP_TLS_DESTRUCTOR_CC
  130. __thread_specific_ptr<_Tp>::__at_thread_exit(void* __p)
  131. {
  132. delete static_cast<pointer>(__p);
  133. }
  134. template <class _Tp>
  135. __thread_specific_ptr<_Tp>::__thread_specific_ptr()
  136. {
  137. int __ec =
  138. __libcpp_tls_create(&__key_, &__thread_specific_ptr::__at_thread_exit);
  139. if (__ec)
  140. __throw_system_error(__ec, "__thread_specific_ptr construction failed");
  141. }
  142. template <class _Tp>
  143. __thread_specific_ptr<_Tp>::~__thread_specific_ptr()
  144. {
  145. // __thread_specific_ptr is only created with a static storage duration
  146. // so this destructor is only invoked during program termination. Invoking
  147. // pthread_key_delete(__key_) may prevent other threads from deleting their
  148. // thread local data. For this reason we leak the key.
  149. }
  150. template <class _Tp>
  151. void
  152. __thread_specific_ptr<_Tp>::set_pointer(pointer __p)
  153. {
  154. _LIBCPP_ASSERT(get() == nullptr,
  155. "Attempting to overwrite thread local data");
  156. std::__libcpp_tls_set(__key_, __p);
  157. }
  158. template<>
  159. struct _LIBCPP_TEMPLATE_VIS hash<__thread_id>
  160. : public __unary_function<__thread_id, size_t>
  161. {
  162. _LIBCPP_INLINE_VISIBILITY
  163. size_t operator()(__thread_id __v) const _NOEXCEPT
  164. {
  165. return hash<__libcpp_thread_id>()(__v.__id_);
  166. }
  167. };
  168. template<class _CharT, class _Traits>
  169. _LIBCPP_INLINE_VISIBILITY
  170. basic_ostream<_CharT, _Traits>&
  171. operator<<(basic_ostream<_CharT, _Traits>& __os, __thread_id __id)
  172. {return __os << __id.__id_;}
  173. class _LIBCPP_TYPE_VIS thread
  174. {
  175. __libcpp_thread_t __t_;
  176. thread(const thread&);
  177. thread& operator=(const thread&);
  178. public:
  179. typedef __thread_id id;
  180. typedef __libcpp_thread_t native_handle_type;
  181. _LIBCPP_INLINE_VISIBILITY
  182. thread() _NOEXCEPT : __t_(_LIBCPP_NULL_THREAD) {}
  183. #ifndef _LIBCPP_CXX03_LANG
  184. template <class _Fp, class ..._Args,
  185. class = __enable_if_t<!is_same<__remove_cvref_t<_Fp>, thread>::value> >
  186. _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
  187. explicit thread(_Fp&& __f, _Args&&... __args);
  188. #else // _LIBCPP_CXX03_LANG
  189. template <class _Fp>
  190. _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
  191. explicit thread(_Fp __f);
  192. #endif
  193. ~thread();
  194. _LIBCPP_INLINE_VISIBILITY
  195. thread(thread&& __t) _NOEXCEPT : __t_(__t.__t_) {
  196. __t.__t_ = _LIBCPP_NULL_THREAD;
  197. }
  198. _LIBCPP_INLINE_VISIBILITY
  199. thread& operator=(thread&& __t) _NOEXCEPT {
  200. if (!__libcpp_thread_isnull(&__t_))
  201. terminate();
  202. __t_ = __t.__t_;
  203. __t.__t_ = _LIBCPP_NULL_THREAD;
  204. return *this;
  205. }
  206. _LIBCPP_INLINE_VISIBILITY
  207. void swap(thread& __t) _NOEXCEPT {_VSTD::swap(__t_, __t.__t_);}
  208. _LIBCPP_INLINE_VISIBILITY
  209. bool joinable() const _NOEXCEPT {return !__libcpp_thread_isnull(&__t_);}
  210. void join();
  211. void detach();
  212. _LIBCPP_INLINE_VISIBILITY
  213. id get_id() const _NOEXCEPT {return __libcpp_thread_get_id(&__t_);}
  214. _LIBCPP_INLINE_VISIBILITY
  215. native_handle_type native_handle() _NOEXCEPT {return __t_;}
  216. static unsigned hardware_concurrency() _NOEXCEPT;
  217. };
  218. #ifndef _LIBCPP_CXX03_LANG
  219. template <class _TSp, class _Fp, class ..._Args, size_t ..._Indices>
  220. inline _LIBCPP_INLINE_VISIBILITY
  221. void
  222. __thread_execute(tuple<_TSp, _Fp, _Args...>& __t, __tuple_indices<_Indices...>)
  223. {
  224. _VSTD::__invoke(_VSTD::move(_VSTD::get<1>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);
  225. }
  226. template <class _Fp>
  227. _LIBCPP_INLINE_VISIBILITY
  228. void* __thread_proxy(void* __vp)
  229. {
  230. // _Fp = tuple< unique_ptr<__thread_struct>, Functor, Args...>
  231. unique_ptr<_Fp> __p(static_cast<_Fp*>(__vp));
  232. __thread_local_data().set_pointer(_VSTD::get<0>(*__p.get()).release());
  233. typedef typename __make_tuple_indices<tuple_size<_Fp>::value, 2>::type _Index;
  234. _VSTD::__thread_execute(*__p.get(), _Index());
  235. return nullptr;
  236. }
  237. template <class _Fp, class ..._Args,
  238. class
  239. >
  240. thread::thread(_Fp&& __f, _Args&&... __args)
  241. {
  242. typedef unique_ptr<__thread_struct> _TSPtr;
  243. _TSPtr __tsp(new __thread_struct);
  244. typedef tuple<_TSPtr, typename decay<_Fp>::type, typename decay<_Args>::type...> _Gp;
  245. unique_ptr<_Gp> __p(
  246. new _Gp(_VSTD::move(__tsp),
  247. _VSTD::forward<_Fp>(__f),
  248. _VSTD::forward<_Args>(__args)...));
  249. int __ec = _VSTD::__libcpp_thread_create(&__t_, &__thread_proxy<_Gp>, __p.get());
  250. if (__ec == 0)
  251. __p.release();
  252. else
  253. __throw_system_error(__ec, "thread constructor failed");
  254. }
  255. #else // _LIBCPP_CXX03_LANG
  256. template <class _Fp>
  257. struct __thread_invoke_pair {
  258. // This type is used to pass memory for thread local storage and a functor
  259. // to a newly created thread because std::pair doesn't work with
  260. // std::unique_ptr in C++03.
  261. __thread_invoke_pair(_Fp& __f) : __tsp_(new __thread_struct), __fn_(__f) {}
  262. unique_ptr<__thread_struct> __tsp_;
  263. _Fp __fn_;
  264. };
  265. template <class _Fp>
  266. _LIBCPP_HIDE_FROM_ABI void* __thread_proxy_cxx03(void* __vp)
  267. {
  268. unique_ptr<_Fp> __p(static_cast<_Fp*>(__vp));
  269. __thread_local_data().set_pointer(__p->__tsp_.release());
  270. (__p->__fn_)();
  271. return nullptr;
  272. }
  273. template <class _Fp>
  274. thread::thread(_Fp __f)
  275. {
  276. typedef __thread_invoke_pair<_Fp> _InvokePair;
  277. typedef unique_ptr<_InvokePair> _PairPtr;
  278. _PairPtr __pp(new _InvokePair(__f));
  279. int __ec = _VSTD::__libcpp_thread_create(&__t_, &__thread_proxy_cxx03<_InvokePair>, __pp.get());
  280. if (__ec == 0)
  281. __pp.release();
  282. else
  283. __throw_system_error(__ec, "thread constructor failed");
  284. }
  285. #endif // _LIBCPP_CXX03_LANG
  286. inline _LIBCPP_INLINE_VISIBILITY
  287. void swap(thread& __x, thread& __y) _NOEXCEPT {__x.swap(__y);}
  288. namespace this_thread
  289. {
  290. _LIBCPP_FUNC_VIS void sleep_for(const chrono::nanoseconds& __ns);
  291. template <class _Rep, class _Period>
  292. _LIBCPP_HIDE_FROM_ABI void
  293. sleep_for(const chrono::duration<_Rep, _Period>& __d)
  294. {
  295. if (__d > chrono::duration<_Rep, _Period>::zero())
  296. {
  297. // The standard guarantees a 64bit signed integer resolution for nanoseconds,
  298. // so use INT64_MAX / 1e9 as cut-off point. Use a constant to avoid <climits>
  299. // and issues with long double folding on PowerPC with GCC.
  300. _LIBCPP_CONSTEXPR chrono::duration<long double> _Max =
  301. chrono::duration<long double>(9223372036.0L);
  302. chrono::nanoseconds __ns;
  303. if (__d < _Max)
  304. {
  305. __ns = chrono::duration_cast<chrono::nanoseconds>(__d);
  306. if (__ns < __d)
  307. ++__ns;
  308. }
  309. else
  310. __ns = chrono::nanoseconds::max();
  311. this_thread::sleep_for(__ns);
  312. }
  313. }
  314. template <class _Clock, class _Duration>
  315. _LIBCPP_HIDE_FROM_ABI void
  316. sleep_until(const chrono::time_point<_Clock, _Duration>& __t)
  317. {
  318. mutex __mut;
  319. condition_variable __cv;
  320. unique_lock<mutex> __lk(__mut);
  321. while (_Clock::now() < __t)
  322. __cv.wait_until(__lk, __t);
  323. }
  324. template <class _Duration>
  325. inline _LIBCPP_INLINE_VISIBILITY
  326. void
  327. sleep_until(const chrono::time_point<chrono::steady_clock, _Duration>& __t)
  328. {
  329. this_thread::sleep_for(__t - chrono::steady_clock::now());
  330. }
  331. inline _LIBCPP_INLINE_VISIBILITY
  332. void yield() _NOEXCEPT {__libcpp_thread_yield();}
  333. } // namespace this_thread
  334. _LIBCPP_END_NAMESPACE_STD
  335. _LIBCPP_POP_MACROS
  336. #if !defined(_LIBCPP_REMOVE_TRANSITIVE_INCLUDES) && _LIBCPP_STD_VER <= 17
  337. # include <chrono>
  338. #endif
  339. #if !defined(_LIBCPP_REMOVE_TRANSITIVE_INCLUDES) && _LIBCPP_STD_VER <= 20
  340. # include <functional>
  341. #endif
  342. #endif // _LIBCPP_THREAD