thread.h 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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_THREAD_H
  10. #define _LIBCPP___THREAD_THREAD_H
  11. #include <__condition_variable/condition_variable.h>
  12. #include <__config>
  13. #include <__exception/terminate.h>
  14. #include <__functional/hash.h>
  15. #include <__functional/unary_function.h>
  16. #include <__memory/unique_ptr.h>
  17. #include <__mutex/mutex.h>
  18. #include <__system_error/system_error.h>
  19. #include <__thread/id.h>
  20. #include <__threading_support>
  21. #include <__utility/forward.h>
  22. #include <iosfwd>
  23. #include <tuple>
  24. #ifndef _LIBCPP_HAS_NO_LOCALIZATION
  25. # include <locale>
  26. # include <sstream>
  27. #endif
  28. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  29. # pragma GCC system_header
  30. #endif
  31. _LIBCPP_BEGIN_NAMESPACE_STD
  32. template <class _Tp> class __thread_specific_ptr;
  33. class _LIBCPP_EXPORTED_FROM_ABI __thread_struct;
  34. class _LIBCPP_HIDDEN __thread_struct_imp;
  35. class __assoc_sub_state;
  36. _LIBCPP_EXPORTED_FROM_ABI __thread_specific_ptr<__thread_struct>& __thread_local_data();
  37. class _LIBCPP_EXPORTED_FROM_ABI __thread_struct
  38. {
  39. __thread_struct_imp* __p_;
  40. __thread_struct(const __thread_struct&);
  41. __thread_struct& operator=(const __thread_struct&);
  42. public:
  43. __thread_struct();
  44. ~__thread_struct();
  45. void notify_all_at_thread_exit(condition_variable*, mutex*);
  46. void __make_ready_at_thread_exit(__assoc_sub_state*);
  47. };
  48. template <class _Tp>
  49. class __thread_specific_ptr
  50. {
  51. __libcpp_tls_key __key_;
  52. // Only __thread_local_data() may construct a __thread_specific_ptr
  53. // and only with _Tp == __thread_struct.
  54. static_assert((is_same<_Tp, __thread_struct>::value), "");
  55. __thread_specific_ptr();
  56. friend _LIBCPP_EXPORTED_FROM_ABI __thread_specific_ptr<__thread_struct>& __thread_local_data();
  57. __thread_specific_ptr(const __thread_specific_ptr&);
  58. __thread_specific_ptr& operator=(const __thread_specific_ptr&);
  59. _LIBCPP_HIDDEN static void _LIBCPP_TLS_DESTRUCTOR_CC __at_thread_exit(void*);
  60. public:
  61. typedef _Tp* pointer;
  62. ~__thread_specific_ptr();
  63. _LIBCPP_INLINE_VISIBILITY
  64. pointer get() const {return static_cast<_Tp*>(__libcpp_tls_get(__key_));}
  65. _LIBCPP_INLINE_VISIBILITY
  66. pointer operator*() const {return *get();}
  67. _LIBCPP_INLINE_VISIBILITY
  68. pointer operator->() const {return get();}
  69. void set_pointer(pointer __p);
  70. };
  71. template <class _Tp>
  72. void _LIBCPP_TLS_DESTRUCTOR_CC
  73. __thread_specific_ptr<_Tp>::__at_thread_exit(void* __p)
  74. {
  75. delete static_cast<pointer>(__p);
  76. }
  77. template <class _Tp>
  78. __thread_specific_ptr<_Tp>::__thread_specific_ptr()
  79. {
  80. int __ec =
  81. __libcpp_tls_create(&__key_, &__thread_specific_ptr::__at_thread_exit);
  82. if (__ec)
  83. __throw_system_error(__ec, "__thread_specific_ptr construction failed");
  84. }
  85. template <class _Tp>
  86. __thread_specific_ptr<_Tp>::~__thread_specific_ptr()
  87. {
  88. // __thread_specific_ptr is only created with a static storage duration
  89. // so this destructor is only invoked during program termination. Invoking
  90. // pthread_key_delete(__key_) may prevent other threads from deleting their
  91. // thread local data. For this reason we leak the key.
  92. }
  93. template <class _Tp>
  94. void
  95. __thread_specific_ptr<_Tp>::set_pointer(pointer __p)
  96. {
  97. _LIBCPP_ASSERT_UNCATEGORIZED(get() == nullptr,
  98. "Attempting to overwrite thread local data");
  99. std::__libcpp_tls_set(__key_, __p);
  100. }
  101. template<>
  102. struct _LIBCPP_TEMPLATE_VIS hash<__thread_id>
  103. : public __unary_function<__thread_id, size_t>
  104. {
  105. _LIBCPP_INLINE_VISIBILITY
  106. size_t operator()(__thread_id __v) const _NOEXCEPT
  107. {
  108. return hash<__libcpp_thread_id>()(__v.__id_);
  109. }
  110. };
  111. #ifndef _LIBCPP_HAS_NO_LOCALIZATION
  112. template <class _CharT, class _Traits>
  113. _LIBCPP_INLINE_VISIBILITY basic_ostream<_CharT, _Traits>&
  114. operator<<(basic_ostream<_CharT, _Traits>& __os, __thread_id __id) {
  115. // [thread.thread.id]/9
  116. // Effects: Inserts the text representation for charT of id into out.
  117. //
  118. // [thread.thread.id]/2
  119. // The text representation for the character type charT of an
  120. // object of type thread::id is an unspecified sequence of charT
  121. // such that, for two objects of type thread::id x and y, if
  122. // x == y is true, the thread::id objects have the same text
  123. // representation, and if x != y is true, the thread::id objects
  124. // have distinct text representations.
  125. //
  126. // Since various flags in the output stream can affect how the
  127. // thread id is represented (e.g. numpunct or showbase), we
  128. // use a temporary stream instead and just output the thread
  129. // id representation as a string.
  130. basic_ostringstream<_CharT, _Traits> __sstr;
  131. __sstr.imbue(locale::classic());
  132. __sstr << __id.__id_;
  133. return __os << __sstr.str();
  134. }
  135. #endif // _LIBCPP_HAS_NO_LOCALIZATION
  136. class _LIBCPP_EXPORTED_FROM_ABI thread
  137. {
  138. __libcpp_thread_t __t_;
  139. thread(const thread&);
  140. thread& operator=(const thread&);
  141. public:
  142. typedef __thread_id id;
  143. typedef __libcpp_thread_t native_handle_type;
  144. _LIBCPP_INLINE_VISIBILITY
  145. thread() _NOEXCEPT : __t_(_LIBCPP_NULL_THREAD) {}
  146. #ifndef _LIBCPP_CXX03_LANG
  147. template <class _Fp, class ..._Args,
  148. class = __enable_if_t<!is_same<__remove_cvref_t<_Fp>, thread>::value> >
  149. _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
  150. explicit thread(_Fp&& __f, _Args&&... __args);
  151. #else // _LIBCPP_CXX03_LANG
  152. template <class _Fp>
  153. _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS
  154. explicit thread(_Fp __f);
  155. #endif
  156. ~thread();
  157. _LIBCPP_INLINE_VISIBILITY
  158. thread(thread&& __t) _NOEXCEPT : __t_(__t.__t_) {
  159. __t.__t_ = _LIBCPP_NULL_THREAD;
  160. }
  161. _LIBCPP_INLINE_VISIBILITY
  162. thread& operator=(thread&& __t) _NOEXCEPT {
  163. if (!__libcpp_thread_isnull(&__t_))
  164. terminate();
  165. __t_ = __t.__t_;
  166. __t.__t_ = _LIBCPP_NULL_THREAD;
  167. return *this;
  168. }
  169. _LIBCPP_INLINE_VISIBILITY
  170. void swap(thread& __t) _NOEXCEPT {_VSTD::swap(__t_, __t.__t_);}
  171. _LIBCPP_INLINE_VISIBILITY
  172. bool joinable() const _NOEXCEPT {return !__libcpp_thread_isnull(&__t_);}
  173. void join();
  174. void detach();
  175. _LIBCPP_INLINE_VISIBILITY
  176. id get_id() const _NOEXCEPT {return __libcpp_thread_get_id(&__t_);}
  177. _LIBCPP_INLINE_VISIBILITY
  178. native_handle_type native_handle() _NOEXCEPT {return __t_;}
  179. static unsigned hardware_concurrency() _NOEXCEPT;
  180. };
  181. #ifndef _LIBCPP_CXX03_LANG
  182. template <class _TSp, class _Fp, class ..._Args, size_t ..._Indices>
  183. inline _LIBCPP_INLINE_VISIBILITY
  184. void
  185. __thread_execute(tuple<_TSp, _Fp, _Args...>& __t, __tuple_indices<_Indices...>)
  186. {
  187. _VSTD::__invoke(_VSTD::move(_VSTD::get<1>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...);
  188. }
  189. template <class _Fp>
  190. _LIBCPP_INLINE_VISIBILITY
  191. void* __thread_proxy(void* __vp)
  192. {
  193. // _Fp = tuple< unique_ptr<__thread_struct>, Functor, Args...>
  194. unique_ptr<_Fp> __p(static_cast<_Fp*>(__vp));
  195. __thread_local_data().set_pointer(_VSTD::get<0>(*__p.get()).release());
  196. typedef typename __make_tuple_indices<tuple_size<_Fp>::value, 2>::type _Index;
  197. _VSTD::__thread_execute(*__p.get(), _Index());
  198. return nullptr;
  199. }
  200. template <class _Fp, class ..._Args,
  201. class
  202. >
  203. thread::thread(_Fp&& __f, _Args&&... __args)
  204. {
  205. typedef unique_ptr<__thread_struct> _TSPtr;
  206. _TSPtr __tsp(new __thread_struct);
  207. typedef tuple<_TSPtr, __decay_t<_Fp>, __decay_t<_Args>...> _Gp;
  208. unique_ptr<_Gp> __p(
  209. new _Gp(_VSTD::move(__tsp),
  210. _VSTD::forward<_Fp>(__f),
  211. _VSTD::forward<_Args>(__args)...));
  212. int __ec = _VSTD::__libcpp_thread_create(&__t_, &__thread_proxy<_Gp>, __p.get());
  213. if (__ec == 0)
  214. __p.release();
  215. else
  216. __throw_system_error(__ec, "thread constructor failed");
  217. }
  218. #else // _LIBCPP_CXX03_LANG
  219. template <class _Fp>
  220. struct __thread_invoke_pair {
  221. // This type is used to pass memory for thread local storage and a functor
  222. // to a newly created thread because std::pair doesn't work with
  223. // std::unique_ptr in C++03.
  224. _LIBCPP_HIDE_FROM_ABI __thread_invoke_pair(_Fp& __f) : __tsp_(new __thread_struct), __fn_(__f) {}
  225. unique_ptr<__thread_struct> __tsp_;
  226. _Fp __fn_;
  227. };
  228. template <class _Fp>
  229. _LIBCPP_HIDE_FROM_ABI void* __thread_proxy_cxx03(void* __vp)
  230. {
  231. unique_ptr<_Fp> __p(static_cast<_Fp*>(__vp));
  232. __thread_local_data().set_pointer(__p->__tsp_.release());
  233. (__p->__fn_)();
  234. return nullptr;
  235. }
  236. template <class _Fp>
  237. thread::thread(_Fp __f)
  238. {
  239. typedef __thread_invoke_pair<_Fp> _InvokePair;
  240. typedef unique_ptr<_InvokePair> _PairPtr;
  241. _PairPtr __pp(new _InvokePair(__f));
  242. int __ec = _VSTD::__libcpp_thread_create(&__t_, &__thread_proxy_cxx03<_InvokePair>, __pp.get());
  243. if (__ec == 0)
  244. __pp.release();
  245. else
  246. __throw_system_error(__ec, "thread constructor failed");
  247. }
  248. #endif // _LIBCPP_CXX03_LANG
  249. inline _LIBCPP_INLINE_VISIBILITY
  250. void swap(thread& __x, thread& __y) _NOEXCEPT {__x.swap(__y);}
  251. _LIBCPP_END_NAMESPACE_STD
  252. #endif // _LIBCPP___THREAD_THREAD_H