thread 11 KB

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