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