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