thread.h 8.7 KB

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