1 //===----------------------------------------------------------------------===// 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 <condition_variable> 14 #include <thread> 15 16 #if defined(__ELF__) && defined(_LIBCPP_LINK_PTHREAD_LIB) 17 # pragma comment(lib, "pthread") 18 #endif 19 20 _LIBCPP_PUSH_MACROS 21 #include <__undef_macros> 22 23 _LIBCPP_BEGIN_NAMESPACE_STD 24 25 // ~condition_variable is defined elsewhere. 26 27 void 28 condition_variable::notify_one() noexcept 29 { 30 __libcpp_condvar_signal(&__cv_); 31 } 32 33 void 34 condition_variable::notify_all() noexcept 35 { 36 __libcpp_condvar_broadcast(&__cv_); 37 } 38 39 void 40 condition_variable::wait(unique_lock<mutex>& lk) noexcept 41 { 42 if (!lk.owns_lock()) 43 __throw_system_error(EPERM, 44 "condition_variable::wait: mutex not locked"); 45 int ec = __libcpp_condvar_wait(&__cv_, lk.mutex()->native_handle()); 46 if (ec) 47 __throw_system_error(ec, "condition_variable wait failed"); 48 } 49 50 void 51 condition_variable::__do_timed_wait(unique_lock<mutex>& lk, 52 chrono::time_point<chrono::system_clock, chrono::nanoseconds> tp) noexcept 53 { 54 using namespace chrono; 55 if (!lk.owns_lock()) 56 __throw_system_error(EPERM, 57 "condition_variable::timed wait: mutex not locked"); 58 nanoseconds d = tp.time_since_epoch(); 59 if (d > nanoseconds(0x59682F000000E941)) 60 d = nanoseconds(0x59682F000000E941); 61 __libcpp_timespec_t ts; 62 seconds s = duration_cast<seconds>(d); 63 typedef decltype(ts.tv_sec) ts_sec; 64 _LIBCPP_CONSTEXPR ts_sec ts_sec_max = numeric_limits<ts_sec>::max(); 65 if (s.count() < ts_sec_max) 66 { 67 ts.tv_sec = static_cast<ts_sec>(s.count()); 68 ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((d - s).count()); 69 } 70 else 71 { 72 ts.tv_sec = ts_sec_max; 73 ts.tv_nsec = giga::num - 1; 74 } 75 int ec = __libcpp_condvar_timedwait(&__cv_, lk.mutex()->native_handle(), &ts); 76 if (ec != 0 && ec != ETIMEDOUT) 77 __throw_system_error(ec, "condition_variable timed_wait failed"); 78 } 79 80 void 81 notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk) 82 { 83 auto& tl_ptr = __thread_local_data(); 84 // If this thread was not created using std::thread then it will not have 85 // previously allocated. 86 if (tl_ptr.get() == nullptr) { 87 tl_ptr.set_pointer(new __thread_struct); 88 } 89 __thread_local_data()->notify_all_at_thread_exit(&cond, lk.release()); 90 } 91 92 _LIBCPP_END_NAMESPACE_STD 93 94 _LIBCPP_POP_MACROS 95 96 #endif // !_LIBCPP_HAS_NO_THREADS 97