1 // thread -*- C++ -*-
2 
3 // Copyright (C) 2008-2021 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library.  This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
9 // any later version.
10 
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
19 
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
23 // <http://www.gnu.org/licenses/>.
24 
25 
26 #define _GLIBCXX_THREAD_ABI_COMPAT 1
27 #include <memory> // include this first so <thread> can use shared_ptr
28 #include <thread>
29 #include <system_error>
30 #include <cerrno>
31 #include <cxxabi_forced.h>
32 
33 #ifndef _GLIBCXX_USE_NANOSLEEP
34 # ifdef _GLIBCXX_HAVE_SLEEP
35 #  include <unistd.h>
36 # elif defined(_GLIBCXX_HAVE_WIN32_SLEEP)
37 #  include <windows.h>
38 # elif defined _GLIBCXX_NO_SLEEP && defined _GLIBCXX_HAS_GTHREADS
39 // We expect to be able to sleep for targets that support multiple threads:
40 #  error "No sleep function known for this target"
41 # endif
42 #endif
43 
44 #ifdef _GLIBCXX_HAS_GTHREADS
45 
46 #if defined(_GLIBCXX_USE_GET_NPROCS)
47 # include <sys/sysinfo.h>
48 # define _GLIBCXX_NPROCS get_nprocs()
49 #elif defined(_GLIBCXX_USE_PTHREADS_NUM_PROCESSORS_NP)
50 # define _GLIBCXX_NPROCS pthread_num_processors_np()
51 #elif defined(_GLIBCXX_USE_SYSCTL_HW_NCPU)
52 # include <stddef.h>
53 # include <sys/sysctl.h>
get_nprocs()54 static inline int get_nprocs()
55 {
56  int count;
57  size_t size = sizeof(count);
58  int mib[] = { CTL_HW, HW_NCPU };
59  if (!sysctl(mib, 2, &count, &size, NULL, 0))
60    return count;
61  return 0;
62 }
63 # define _GLIBCXX_NPROCS get_nprocs()
64 #elif defined(_GLIBCXX_USE_SC_NPROCESSORS_ONLN)
65 # include <unistd.h>
66 # define _GLIBCXX_NPROCS sysconf(_SC_NPROCESSORS_ONLN)
67 #elif defined(_GLIBCXX_USE_SC_NPROC_ONLN)
68 # include <unistd.h>
69 # define _GLIBCXX_NPROCS sysconf(_SC_NPROC_ONLN)
70 #else
71 # define _GLIBCXX_NPROCS 0
72 #endif
73 
74 namespace std _GLIBCXX_VISIBILITY(default)
75 {
76   extern "C"
77   {
78     static void*
execute_native_thread_routine(void * __p)79     execute_native_thread_routine(void* __p)
80     {
81       thread::_State_ptr __t{ static_cast<thread::_State*>(__p) };
82       __t->_M_run();
83       return nullptr;
84     }
85 
86 #if _GLIBCXX_THREAD_ABI_COMPAT
87     static void*
execute_native_thread_routine_compat(void * __p)88     execute_native_thread_routine_compat(void* __p)
89     {
90       thread::_Impl_base* __t = static_cast<thread::_Impl_base*>(__p);
91       thread::__shared_base_type __local;
92       // Now that a new thread has been created we can transfer ownership of
93       // the thread state to a local object, breaking the reference cycle
94       // created in thread::_M_start_thread.
95       __local.swap(__t->_M_this_ptr);
96       __t->_M_run();
97       return nullptr;
98     }
99 #endif
100   } // extern "C"
101 
102 _GLIBCXX_BEGIN_NAMESPACE_VERSION
103 
104   thread::_State::~_State() = default;
105 
106   void
join()107   thread::join()
108   {
109     int __e = EINVAL;
110 
111     if (_M_id != id())
112       __e = __gthread_join(_M_id._M_thread, 0);
113 
114     if (__e)
115       __throw_system_error(__e);
116 
117     _M_id = id();
118   }
119 
120   void
detach()121   thread::detach()
122   {
123     int __e = EINVAL;
124 
125     if (_M_id != id())
126       __e = __gthread_detach(_M_id._M_thread);
127 
128     if (__e)
129       __throw_system_error(__e);
130 
131     _M_id = id();
132   }
133 
134   void
_M_start_thread(_State_ptr state,void (*)())135   thread::_M_start_thread(_State_ptr state, void (*)())
136   {
137     if (!__gthread_active_p())
138       {
139 #if __cpp_exceptions
140 	throw system_error(make_error_code(errc::operation_not_permitted),
141 			   "Enable multithreading to use std::thread");
142 #else
143 	__builtin_abort();
144 #endif
145       }
146 
147     const int err = __gthread_create(&_M_id._M_thread,
148 				     &execute_native_thread_routine,
149 				     state.get());
150     if (err)
151       __throw_system_error(err);
152     state.release();
153   }
154 
155 #if _GLIBCXX_THREAD_ABI_COMPAT
156   void
_M_start_thread(__shared_base_type __b)157   thread::_M_start_thread(__shared_base_type __b)
158   {
159     if (!__gthread_active_p())
160 #if __cpp_exceptions
161       throw system_error(make_error_code(errc::operation_not_permitted),
162 			 "Enable multithreading to use std::thread");
163 #else
164       __throw_system_error(int(errc::operation_not_permitted));
165 #endif
166 
167     _M_start_thread(std::move(__b), nullptr);
168   }
169 
170   void
_M_start_thread(__shared_base_type __b,void (*)())171   thread::_M_start_thread(__shared_base_type __b, void (*)())
172   {
173     auto ptr = __b.get();
174     // Create a reference cycle that will be broken in the new thread.
175     ptr->_M_this_ptr = std::move(__b);
176     int __e = __gthread_create(&_M_id._M_thread,
177 			       &execute_native_thread_routine_compat, ptr);
178     if (__e)
179     {
180       ptr->_M_this_ptr.reset();  // break reference cycle, destroying *ptr.
181       __throw_system_error(__e);
182     }
183   }
184 #endif
185 
186   unsigned int
hardware_concurrency()187   thread::hardware_concurrency() noexcept
188   {
189     int __n = _GLIBCXX_NPROCS;
190     if (__n < 0)
191       __n = 0;
192     return __n;
193   }
194 
195 _GLIBCXX_END_NAMESPACE_VERSION
196 } // namespace std
197 
198 #endif // _GLIBCXX_HAS_GTHREADS
199 
200 #ifndef _GLIBCXX_NO_SLEEP
201 namespace std _GLIBCXX_VISIBILITY(default)
202 {
203 _GLIBCXX_BEGIN_NAMESPACE_VERSION
204 namespace this_thread
205 {
206   void
__sleep_for(chrono::seconds __s,chrono::nanoseconds __ns)207   __sleep_for(chrono::seconds __s, chrono::nanoseconds __ns)
208   {
209 #ifdef _GLIBCXX_USE_NANOSLEEP
210     struct ::timespec __ts =
211       {
212 	static_cast<std::time_t>(__s.count()),
213 	static_cast<long>(__ns.count())
214       };
215     while (::nanosleep(&__ts, &__ts) == -1 && errno == EINTR)
216       { }
217 #elif defined(_GLIBCXX_HAVE_SLEEP)
218     const auto target = chrono::steady_clock::now() + __s + __ns;
219     while (true)
220       {
221 	unsigned secs = __s.count();
222 	if (__ns.count() > 0)
223 	  {
224 # ifdef _GLIBCXX_HAVE_USLEEP
225 	    long us = __ns.count() / 1000;
226 	    if (us == 0)
227 	      us = 1;
228 	    ::usleep(us);
229 # else
230 	    if (__ns.count() > 1000000 || secs == 0)
231 	      ++secs; // No sub-second sleep function, so round up.
232 # endif
233 	  }
234 
235 	if (secs > 0)
236 	  {
237 	    // Sleep in a loop to handle interruption by signals:
238 	    while ((secs = ::sleep(secs)))
239 	      { }
240 	  }
241 	const auto now = chrono::steady_clock::now();
242 	if (now >= target)
243 	  break;
244 	__s = chrono::duration_cast<chrono::seconds>(target - now);
245 	__ns = chrono::duration_cast<chrono::nanoseconds>(target - (now + __s));
246     }
247 #elif defined(_GLIBCXX_HAVE_WIN32_SLEEP)
248     unsigned long ms = __ns.count() / 1000000;
249     if (__ns.count() > 0 && ms == 0)
250       ms = 1;
251     ::Sleep(chrono::milliseconds(__s).count() + ms);
252 #endif
253   }
254 }
255 _GLIBCXX_END_NAMESPACE_VERSION
256 } // namespace std
257 #endif // ! NO_SLEEP
258