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