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