thread 11 KB

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