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