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 11#define _LIBCPP_THREAD 12 13/* 14 15 thread synopsis 16 17namespace std 18{ 19 20class thread 21{ 22public: 23 class id; 24 typedef pthread_t native_handle_type; 25 26 thread() noexcept; 27 template <class F, class ...Args> explicit thread(F&& f, Args&&... args); 28 ~thread(); 29 30 thread(const thread&) = delete; 31 thread(thread&& t) noexcept; 32 33 thread& operator=(const thread&) = delete; 34 thread& operator=(thread&& t) noexcept; 35 36 void swap(thread& t) noexcept; 37 38 bool joinable() const noexcept; 39 void join(); 40 void detach(); 41 id get_id() const noexcept; 42 native_handle_type native_handle(); 43 44 static unsigned hardware_concurrency() noexcept; 45}; 46 47void swap(thread& x, thread& y) noexcept; 48 49class thread::id 50{ 51public: 52 id() noexcept; 53}; 54 55bool operator==(thread::id x, thread::id y) noexcept; 56bool operator!=(thread::id x, thread::id y) noexcept; 57bool operator< (thread::id x, thread::id y) noexcept; 58bool operator<=(thread::id x, thread::id y) noexcept; 59bool operator> (thread::id x, thread::id y) noexcept; 60bool operator>=(thread::id x, thread::id y) noexcept; 61 62template<class charT, class traits> 63basic_ostream<charT, traits>& 64operator<<(basic_ostream<charT, traits>& out, thread::id id); 65 66namespace this_thread 67{ 68 69thread::id get_id() noexcept; 70 71void yield() noexcept; 72 73template <class Clock, class Duration> 74void sleep_until(const chrono::time_point<Clock, Duration>& abs_time); 75 76template <class Rep, class Period> 77void sleep_for(const chrono::duration<Rep, Period>& rel_time); 78 79} // this_thread 80 81} // std 82 83*/ 84 85#include <__assert> // all public C++ headers provide the assertion handler 86#include <__config> 87#include <__mutex_base> 88#include <__thread/poll_with_backoff.h> 89#include <__thread/timed_backoff_policy.h> 90#include <__threading_support> 91#include <__utility/forward.h> 92#include <cstddef> 93#include <iosfwd> 94#include <memory> 95#include <system_error> 96#include <tuple> 97#include <type_traits> 98#include <version> 99 100#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) 101# pragma GCC system_header 102#endif 103 104_LIBCPP_PUSH_MACROS 105#include <__undef_macros> 106 107#ifdef _LIBCPP_HAS_NO_THREADS 108#error <thread> is not supported on this single threaded system 109#else // !_LIBCPP_HAS_NO_THREADS 110 111_LIBCPP_BEGIN_NAMESPACE_STD 112 113template <class _Tp> class __thread_specific_ptr; 114class _LIBCPP_TYPE_VIS __thread_struct; 115class _LIBCPP_HIDDEN __thread_struct_imp; 116class __assoc_sub_state; 117 118_LIBCPP_FUNC_VIS __thread_specific_ptr<__thread_struct>& __thread_local_data(); 119 120class _LIBCPP_TYPE_VIS __thread_struct 121{ 122 __thread_struct_imp* __p_; 123 124 __thread_struct(const __thread_struct&); 125 __thread_struct& operator=(const __thread_struct&); 126public: 127 __thread_struct(); 128 ~__thread_struct(); 129 130 void notify_all_at_thread_exit(condition_variable*, mutex*); 131 void __make_ready_at_thread_exit(__assoc_sub_state*); 132}; 133 134template <class _Tp> 135class __thread_specific_ptr 136{ 137 __libcpp_tls_key __key_; 138 139 // Only __thread_local_data() may construct a __thread_specific_ptr 140 // and only with _Tp == __thread_struct. 141 static_assert((is_same<_Tp, __thread_struct>::value), ""); 142 __thread_specific_ptr(); 143 friend _LIBCPP_FUNC_VIS __thread_specific_ptr<__thread_struct>& __thread_local_data(); 144 145 __thread_specific_ptr(const __thread_specific_ptr&); 146 __thread_specific_ptr& operator=(const __thread_specific_ptr&); 147 148 _LIBCPP_HIDDEN static void _LIBCPP_TLS_DESTRUCTOR_CC __at_thread_exit(void*); 149 150public: 151 typedef _Tp* pointer; 152 153 ~__thread_specific_ptr(); 154 155 _LIBCPP_INLINE_VISIBILITY 156 pointer get() const {return static_cast<_Tp*>(__libcpp_tls_get(__key_));} 157 _LIBCPP_INLINE_VISIBILITY 158 pointer operator*() const {return *get();} 159 _LIBCPP_INLINE_VISIBILITY 160 pointer operator->() const {return get();} 161 void set_pointer(pointer __p); 162}; 163 164template <class _Tp> 165void _LIBCPP_TLS_DESTRUCTOR_CC 166__thread_specific_ptr<_Tp>::__at_thread_exit(void* __p) 167{ 168 delete static_cast<pointer>(__p); 169} 170 171template <class _Tp> 172__thread_specific_ptr<_Tp>::__thread_specific_ptr() 173{ 174 int __ec = 175 __libcpp_tls_create(&__key_, &__thread_specific_ptr::__at_thread_exit); 176 if (__ec) 177 __throw_system_error(__ec, "__thread_specific_ptr construction failed"); 178} 179 180template <class _Tp> 181__thread_specific_ptr<_Tp>::~__thread_specific_ptr() 182{ 183 // __thread_specific_ptr is only created with a static storage duration 184 // so this destructor is only invoked during program termination. Invoking 185 // pthread_key_delete(__key_) may prevent other threads from deleting their 186 // thread local data. For this reason we leak the key. 187} 188 189template <class _Tp> 190void 191__thread_specific_ptr<_Tp>::set_pointer(pointer __p) 192{ 193 _LIBCPP_ASSERT(get() == nullptr, 194 "Attempting to overwrite thread local data"); 195 __libcpp_tls_set(__key_, __p); 196} 197 198template<> 199struct _LIBCPP_TEMPLATE_VIS hash<__thread_id> 200 : public unary_function<__thread_id, size_t> 201{ 202 _LIBCPP_INLINE_VISIBILITY 203 size_t operator()(__thread_id __v) const _NOEXCEPT 204 { 205 return hash<__libcpp_thread_id>()(__v.__id_); 206 } 207}; 208 209template<class _CharT, class _Traits> 210_LIBCPP_INLINE_VISIBILITY 211basic_ostream<_CharT, _Traits>& 212operator<<(basic_ostream<_CharT, _Traits>& __os, __thread_id __id) 213{return __os << __id.__id_;} 214 215class _LIBCPP_TYPE_VIS thread 216{ 217 __libcpp_thread_t __t_; 218 219 thread(const thread&); 220 thread& operator=(const thread&); 221public: 222 typedef __thread_id id; 223 typedef __libcpp_thread_t native_handle_type; 224 225 _LIBCPP_INLINE_VISIBILITY 226 thread() _NOEXCEPT : __t_(_LIBCPP_NULL_THREAD) {} 227#ifndef _LIBCPP_CXX03_LANG 228 template <class _Fp, class ..._Args, 229 class = __enable_if_t<!is_same<__uncvref_t<_Fp>, thread>::value> > 230 _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS 231 explicit thread(_Fp&& __f, _Args&&... __args); 232#else // _LIBCPP_CXX03_LANG 233 template <class _Fp> 234 _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS 235 explicit thread(_Fp __f); 236#endif 237 ~thread(); 238 239 _LIBCPP_INLINE_VISIBILITY 240 thread(thread&& __t) _NOEXCEPT : __t_(__t.__t_) { 241 __t.__t_ = _LIBCPP_NULL_THREAD; 242 } 243 244 _LIBCPP_INLINE_VISIBILITY 245 thread& operator=(thread&& __t) _NOEXCEPT { 246 if (!__libcpp_thread_isnull(&__t_)) 247 terminate(); 248 __t_ = __t.__t_; 249 __t.__t_ = _LIBCPP_NULL_THREAD; 250 return *this; 251 } 252 253 _LIBCPP_INLINE_VISIBILITY 254 void swap(thread& __t) _NOEXCEPT {_VSTD::swap(__t_, __t.__t_);} 255 256 _LIBCPP_INLINE_VISIBILITY 257 bool joinable() const _NOEXCEPT {return !__libcpp_thread_isnull(&__t_);} 258 void join(); 259 void detach(); 260 _LIBCPP_INLINE_VISIBILITY 261 id get_id() const _NOEXCEPT {return __libcpp_thread_get_id(&__t_);} 262 _LIBCPP_INLINE_VISIBILITY 263 native_handle_type native_handle() _NOEXCEPT {return __t_;} 264 265 static unsigned hardware_concurrency() _NOEXCEPT; 266}; 267 268#ifndef _LIBCPP_CXX03_LANG 269 270template <class _TSp, class _Fp, class ..._Args, size_t ..._Indices> 271inline _LIBCPP_INLINE_VISIBILITY 272void 273__thread_execute(tuple<_TSp, _Fp, _Args...>& __t, __tuple_indices<_Indices...>) 274{ 275 _VSTD::__invoke(_VSTD::move(_VSTD::get<1>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...); 276} 277 278template <class _Fp> 279_LIBCPP_INLINE_VISIBILITY 280void* __thread_proxy(void* __vp) 281{ 282 // _Fp = tuple< unique_ptr<__thread_struct>, Functor, Args...> 283 unique_ptr<_Fp> __p(static_cast<_Fp*>(__vp)); 284 __thread_local_data().set_pointer(_VSTD::get<0>(*__p.get()).release()); 285 typedef typename __make_tuple_indices<tuple_size<_Fp>::value, 2>::type _Index; 286 _VSTD::__thread_execute(*__p.get(), _Index()); 287 return nullptr; 288} 289 290template <class _Fp, class ..._Args, 291 class 292 > 293thread::thread(_Fp&& __f, _Args&&... __args) 294{ 295 typedef unique_ptr<__thread_struct> _TSPtr; 296 _TSPtr __tsp(new __thread_struct); 297 typedef tuple<_TSPtr, typename decay<_Fp>::type, typename decay<_Args>::type...> _Gp; 298 unique_ptr<_Gp> __p( 299 new _Gp(_VSTD::move(__tsp), 300 _VSTD::forward<_Fp>(__f), 301 _VSTD::forward<_Args>(__args)...)); 302 int __ec = _VSTD::__libcpp_thread_create(&__t_, &__thread_proxy<_Gp>, __p.get()); 303 if (__ec == 0) 304 __p.release(); 305 else 306 __throw_system_error(__ec, "thread constructor failed"); 307} 308 309#else // _LIBCPP_CXX03_LANG 310 311template <class _Fp> 312struct __thread_invoke_pair { 313 // This type is used to pass memory for thread local storage and a functor 314 // to a newly created thread because std::pair doesn't work with 315 // std::unique_ptr in C++03. 316 __thread_invoke_pair(_Fp& __f) : __tsp_(new __thread_struct), __fn_(__f) {} 317 unique_ptr<__thread_struct> __tsp_; 318 _Fp __fn_; 319}; 320 321template <class _Fp> 322void* __thread_proxy_cxx03(void* __vp) 323{ 324 unique_ptr<_Fp> __p(static_cast<_Fp*>(__vp)); 325 __thread_local_data().set_pointer(__p->__tsp_.release()); 326 (__p->__fn_)(); 327 return nullptr; 328} 329 330template <class _Fp> 331thread::thread(_Fp __f) 332{ 333 334 typedef __thread_invoke_pair<_Fp> _InvokePair; 335 typedef unique_ptr<_InvokePair> _PairPtr; 336 _PairPtr __pp(new _InvokePair(__f)); 337 int __ec = _VSTD::__libcpp_thread_create(&__t_, &__thread_proxy_cxx03<_InvokePair>, __pp.get()); 338 if (__ec == 0) 339 __pp.release(); 340 else 341 __throw_system_error(__ec, "thread constructor failed"); 342} 343 344#endif // _LIBCPP_CXX03_LANG 345 346inline _LIBCPP_INLINE_VISIBILITY 347void swap(thread& __x, thread& __y) _NOEXCEPT {__x.swap(__y);} 348 349namespace this_thread 350{ 351 352_LIBCPP_FUNC_VIS void sleep_for(const chrono::nanoseconds& __ns); 353 354template <class _Rep, class _Period> 355void 356sleep_for(const chrono::duration<_Rep, _Period>& __d) 357{ 358 if (__d > chrono::duration<_Rep, _Period>::zero()) 359 { 360 // The standard guarantees a 64bit signed integer resolution for nanoseconds, 361 // so use INT64_MAX / 1e9 as cut-off point. Use a constant to avoid <climits> 362 // and issues with long double folding on PowerPC with GCC. 363 _LIBCPP_CONSTEXPR chrono::duration<long double> _Max = 364 chrono::duration<long double>(9223372036.0L); 365 chrono::nanoseconds __ns; 366 if (__d < _Max) 367 { 368 __ns = chrono::duration_cast<chrono::nanoseconds>(__d); 369 if (__ns < __d) 370 ++__ns; 371 } 372 else 373 __ns = chrono::nanoseconds::max(); 374 this_thread::sleep_for(__ns); 375 } 376} 377 378template <class _Clock, class _Duration> 379void 380sleep_until(const chrono::time_point<_Clock, _Duration>& __t) 381{ 382 mutex __mut; 383 condition_variable __cv; 384 unique_lock<mutex> __lk(__mut); 385 while (_Clock::now() < __t) 386 __cv.wait_until(__lk, __t); 387} 388 389template <class _Duration> 390inline _LIBCPP_INLINE_VISIBILITY 391void 392sleep_until(const chrono::time_point<chrono::steady_clock, _Duration>& __t) 393{ 394 this_thread::sleep_for(__t - chrono::steady_clock::now()); 395} 396 397inline _LIBCPP_INLINE_VISIBILITY 398void yield() _NOEXCEPT {__libcpp_thread_yield();} 399 400} // namespace this_thread 401 402_LIBCPP_END_NAMESPACE_STD 403 404#endif // !_LIBCPP_HAS_NO_THREADS 405 406_LIBCPP_POP_MACROS 407 408#endif // _LIBCPP_THREAD 409