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