Path: blob/main/contrib/llvm-project/libcxx/src/condition_variable.cpp
35147 views
//===----------------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include <condition_variable>9#include <thread>1011#if defined(__ELF__) && defined(_LIBCPP_LINK_PTHREAD_LIB)12# pragma comment(lib, "pthread")13#endif1415_LIBCPP_PUSH_MACROS16#include <__undef_macros>1718_LIBCPP_BEGIN_NAMESPACE_STD1920// ~condition_variable is defined elsewhere.2122void condition_variable::notify_one() noexcept { __libcpp_condvar_signal(&__cv_); }2324void condition_variable::notify_all() noexcept { __libcpp_condvar_broadcast(&__cv_); }2526void condition_variable::wait(unique_lock<mutex>& lk) noexcept {27if (!lk.owns_lock())28__throw_system_error(EPERM, "condition_variable::wait: mutex not locked");29int ec = __libcpp_condvar_wait(&__cv_, lk.mutex()->native_handle());30if (ec)31__throw_system_error(ec, "condition_variable wait failed");32}3334void condition_variable::__do_timed_wait(unique_lock<mutex>& lk,35chrono::time_point<chrono::system_clock, chrono::nanoseconds> tp) noexcept {36using namespace chrono;37if (!lk.owns_lock())38__throw_system_error(EPERM, "condition_variable::timed wait: mutex not locked");39nanoseconds d = tp.time_since_epoch();40if (d > nanoseconds(0x59682F000000E941))41d = nanoseconds(0x59682F000000E941);42__libcpp_timespec_t ts;43seconds s = duration_cast<seconds>(d);44typedef decltype(ts.tv_sec) ts_sec;45constexpr ts_sec ts_sec_max = numeric_limits<ts_sec>::max();46if (s.count() < ts_sec_max) {47ts.tv_sec = static_cast<ts_sec>(s.count());48ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((d - s).count());49} else {50ts.tv_sec = ts_sec_max;51ts.tv_nsec = giga::num - 1;52}53int ec = __libcpp_condvar_timedwait(&__cv_, lk.mutex()->native_handle(), &ts);54if (ec != 0 && ec != ETIMEDOUT)55__throw_system_error(ec, "condition_variable timed_wait failed");56}5758void notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk) {59auto& tl_ptr = __thread_local_data();60// If this thread was not created using std::thread then it will not have61// previously allocated.62if (tl_ptr.get() == nullptr) {63tl_ptr.set_pointer(new __thread_struct);64}65__thread_local_data()->notify_all_at_thread_exit(&cond, lk.release());66}6768_LIBCPP_END_NAMESPACE_STD6970_LIBCPP_POP_MACROS717273