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