thread 11 KB

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