1 //===------------------------- thread.cpp----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <__thread/poll_with_backoff.h>
10 #include <__thread/timed_backoff_policy.h>
11 #include <exception>
12 #include <future>
13 #include <limits>
14 #include <thread>
15 #include <vector>
16 
17 #if __has_include(<unistd.h>)
18 # include <unistd.h> // for sysconf
19 #endif
20 
21 #if defined(__NetBSD__)
22 #pragma weak pthread_create // Do not create libpthread dependency
23 #endif
24 
25 #if defined(_LIBCPP_WIN32API)
26 #include <windows.h>
27 #endif
28 
29 #if defined(__ELF__) && defined(_LIBCPP_LINK_PTHREAD_LIB)
30 #pragma comment(lib, "pthread")
31 #endif
32 
33 _LIBCPP_BEGIN_NAMESPACE_STD
34 
35 thread::~thread()
36 {
37     if (!__libcpp_thread_isnull(&__t_))
38         terminate();
39 }
40 
41 void
42 thread::join()
43 {
44     int ec = EINVAL;
45     if (!__libcpp_thread_isnull(&__t_))
46     {
47         ec = __libcpp_thread_join(&__t_);
48         if (ec == 0)
49             __t_ = _LIBCPP_NULL_THREAD;
50     }
51 
52     if (ec)
53         __throw_system_error(ec, "thread::join failed");
54 }
55 
56 void
57 thread::detach()
58 {
59     int ec = EINVAL;
60     if (!__libcpp_thread_isnull(&__t_))
61     {
62         ec = __libcpp_thread_detach(&__t_);
63         if (ec == 0)
64             __t_ = _LIBCPP_NULL_THREAD;
65     }
66 
67     if (ec)
68         __throw_system_error(ec, "thread::detach failed");
69 }
70 
71 unsigned
72 thread::hardware_concurrency() noexcept
73 {
74 #if defined(_SC_NPROCESSORS_ONLN)
75     long result = sysconf(_SC_NPROCESSORS_ONLN);
76     // sysconf returns -1 if the name is invalid, the option does not exist or
77     // does not have a definite limit.
78     // if sysconf returns some other negative number, we have no idea
79     // what is going on. Default to something safe.
80     if (result < 0)
81         return 0;
82     return static_cast<unsigned>(result);
83 #elif defined(_LIBCPP_WIN32API)
84     SYSTEM_INFO info;
85     GetSystemInfo(&info);
86     return info.dwNumberOfProcessors;
87 #else  // defined(CTL_HW) && defined(HW_NCPU)
88     // TODO: grovel through /proc or check cpuid on x86 and similar
89     // instructions on other architectures.
90 #   if defined(_LIBCPP_WARNING)
91         _LIBCPP_WARNING("hardware_concurrency not yet implemented")
92 #   else
93 #       warning hardware_concurrency not yet implemented
94 #   endif
95     return 0;  // Means not computable [thread.thread.static]
96 #endif // defined(CTL_HW) && defined(HW_NCPU)
97 }
98 
99 namespace this_thread
100 {
101 
102 void
103 sleep_for(const chrono::nanoseconds& ns)
104 {
105     if (ns > chrono::nanoseconds::zero())
106     {
107         __libcpp_thread_sleep_for(ns);
108     }
109 }
110 
111 }  // this_thread
112 
113 __thread_specific_ptr<__thread_struct>&
114 __thread_local_data()
115 {
116   // Even though __thread_specific_ptr's destructor doesn't actually destroy
117   // anything (see comments there), we can't call it at all because threads may
118   // outlive the static variable and calling its destructor means accessing an
119   // object outside of its lifetime, which is UB.
120   alignas(__thread_specific_ptr<__thread_struct>) static char __b[sizeof(__thread_specific_ptr<__thread_struct>)];
121   static __thread_specific_ptr<__thread_struct>* __p = new (__b) __thread_specific_ptr<__thread_struct>();
122   return *__p;
123 }
124 
125 // __thread_struct_imp
126 
127 template <class T>
128 class _LIBCPP_HIDDEN __hidden_allocator
129 {
130 public:
131     typedef T  value_type;
132 
133     T* allocate(size_t __n)
134         {return static_cast<T*>(::operator new(__n * sizeof(T)));}
135     void deallocate(T* __p, size_t) {::operator delete(static_cast<void*>(__p));}
136 
137     size_t max_size() const {return size_t(~0) / sizeof(T);}
138 };
139 
140 class _LIBCPP_HIDDEN __thread_struct_imp
141 {
142     typedef vector<__assoc_sub_state*,
143                           __hidden_allocator<__assoc_sub_state*> > _AsyncStates;
144     typedef vector<pair<condition_variable*, mutex*>,
145                __hidden_allocator<pair<condition_variable*, mutex*> > > _Notify;
146 
147     _AsyncStates async_states_;
148     _Notify notify_;
149 
150     __thread_struct_imp(const __thread_struct_imp&);
151     __thread_struct_imp& operator=(const __thread_struct_imp&);
152 public:
153     __thread_struct_imp() {}
154     ~__thread_struct_imp();
155 
156     void notify_all_at_thread_exit(condition_variable* cv, mutex* m);
157     void __make_ready_at_thread_exit(__assoc_sub_state* __s);
158 };
159 
160 __thread_struct_imp::~__thread_struct_imp()
161 {
162     for (_Notify::iterator i = notify_.begin(), e = notify_.end();
163             i != e; ++i)
164     {
165         i->first->notify_all();
166         i->second->unlock();
167     }
168     for (_AsyncStates::iterator i = async_states_.begin(), e = async_states_.end();
169             i != e; ++i)
170     {
171         (*i)->__make_ready();
172         (*i)->__release_shared();
173     }
174 }
175 
176 void
177 __thread_struct_imp::notify_all_at_thread_exit(condition_variable* cv, mutex* m)
178 {
179     notify_.push_back(pair<condition_variable*, mutex*>(cv, m));
180 }
181 
182 void
183 __thread_struct_imp::__make_ready_at_thread_exit(__assoc_sub_state* __s)
184 {
185     async_states_.push_back(__s);
186     __s->__add_shared();
187 }
188 
189 // __thread_struct
190 
191 __thread_struct::__thread_struct()
192     : __p_(new __thread_struct_imp)
193 {
194 }
195 
196 __thread_struct::~__thread_struct()
197 {
198     delete __p_;
199 }
200 
201 void
202 __thread_struct::notify_all_at_thread_exit(condition_variable* cv, mutex* m)
203 {
204     __p_->notify_all_at_thread_exit(cv, m);
205 }
206 
207 void
208 __thread_struct::__make_ready_at_thread_exit(__assoc_sub_state* __s)
209 {
210     __p_->__make_ready_at_thread_exit(__s);
211 }
212 
213 _LIBCPP_END_NAMESPACE_STD
214