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