Path: blob/main/system/lib/libcxx/src/condition_variable.cpp
6175 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 <limits>10#include <ratio>11#include <thread>12#include <__chrono/duration.h>13#include <__chrono/system_clock.h>14#include <__chrono/time_point.h>15#include <__system_error/throw_system_error.h>1617#if defined(__ELF__) && defined(_LIBCPP_LINK_PTHREAD_LIB)18# pragma comment(lib, "pthread")19#endif2021_LIBCPP_PUSH_MACROS22#include <__undef_macros>2324_LIBCPP_BEGIN_NAMESPACE_STD2526// ~condition_variable is defined elsewhere.2728void condition_variable::notify_one() noexcept { __libcpp_condvar_signal(&__cv_); }2930void condition_variable::notify_all() noexcept { __libcpp_condvar_broadcast(&__cv_); }3132void condition_variable::wait(unique_lock<mutex>& lk) noexcept {33if (!lk.owns_lock())34std::__throw_system_error(EPERM, "condition_variable::wait: mutex not locked");35int ec = __libcpp_condvar_wait(&__cv_, lk.mutex()->native_handle());36if (ec)37std::__throw_system_error(ec, "condition_variable wait failed");38}3940void condition_variable::__do_timed_wait(unique_lock<mutex>& lk,41chrono::time_point<chrono::system_clock, chrono::nanoseconds> tp) noexcept {42using namespace chrono;43if (!lk.owns_lock())44std::__throw_system_error(EPERM, "condition_variable::timed wait: mutex not locked");45nanoseconds d = tp.time_since_epoch();46if (d > nanoseconds(0x59682F000000E941))47d = nanoseconds(0x59682F000000E941);48__libcpp_timespec_t ts;49seconds s = duration_cast<seconds>(d);50typedef decltype(ts.tv_sec) ts_sec;51constexpr ts_sec ts_sec_max = numeric_limits<ts_sec>::max();52if (s.count() < ts_sec_max) {53ts.tv_sec = static_cast<ts_sec>(s.count());54ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((d - s).count());55} else {56ts.tv_sec = ts_sec_max;57ts.tv_nsec = giga::num - 1;58}59int ec = __libcpp_condvar_timedwait(&__cv_, lk.mutex()->native_handle(), &ts);60if (ec != 0 && ec != ETIMEDOUT)61std::__throw_system_error(ec, "condition_variable timed_wait failed");62}6364void notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk) {65auto& tl_ptr = __thread_local_data();66// If this thread was not created using std::thread then it will not have67// previously allocated.68if (tl_ptr.get() == nullptr) {69tl_ptr.set_pointer(new __thread_struct);70}71__thread_local_data()->notify_all_at_thread_exit(&cond, lk.release());72}7374_LIBCPP_END_NAMESPACE_STD7576_LIBCPP_POP_MACROS777879