[flang] Fix length handling in character kind implicit conversion (#74586)
[llvm-project.git] / libcxx / src / condition_variable.cpp
blob33e19568b4744f1ed633b1797a3cb6976759a268
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 //===----------------------------------------------------------------------===//
9 #include <condition_variable>
10 #include <thread>
12 #if defined(__ELF__) && defined(_LIBCPP_LINK_PTHREAD_LIB)
13 # pragma comment(lib, "pthread")
14 #endif
16 _LIBCPP_PUSH_MACROS
17 #include <__undef_macros>
19 _LIBCPP_BEGIN_NAMESPACE_STD
21 // ~condition_variable is defined elsewhere.
23 void
24 condition_variable::notify_one() noexcept
26 __libcpp_condvar_signal(&__cv_);
29 void
30 condition_variable::notify_all() noexcept
32 __libcpp_condvar_broadcast(&__cv_);
35 void
36 condition_variable::wait(unique_lock<mutex>& lk) noexcept
38 if (!lk.owns_lock())
39 __throw_system_error(EPERM,
40 "condition_variable::wait: mutex not locked");
41 int ec = __libcpp_condvar_wait(&__cv_, lk.mutex()->native_handle());
42 if (ec)
43 __throw_system_error(ec, "condition_variable wait failed");
46 void
47 condition_variable::__do_timed_wait(unique_lock<mutex>& lk,
48 chrono::time_point<chrono::system_clock, chrono::nanoseconds> tp) noexcept
50 using namespace chrono;
51 if (!lk.owns_lock())
52 __throw_system_error(EPERM,
53 "condition_variable::timed wait: mutex not locked");
54 nanoseconds d = tp.time_since_epoch();
55 if (d > nanoseconds(0x59682F000000E941))
56 d = nanoseconds(0x59682F000000E941);
57 __libcpp_timespec_t ts;
58 seconds s = duration_cast<seconds>(d);
59 typedef decltype(ts.tv_sec) ts_sec;
60 constexpr ts_sec ts_sec_max = numeric_limits<ts_sec>::max();
61 if (s.count() < ts_sec_max)
63 ts.tv_sec = static_cast<ts_sec>(s.count());
64 ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((d - s).count());
66 else
68 ts.tv_sec = ts_sec_max;
69 ts.tv_nsec = giga::num - 1;
71 int ec = __libcpp_condvar_timedwait(&__cv_, lk.mutex()->native_handle(), &ts);
72 if (ec != 0 && ec != ETIMEDOUT)
73 __throw_system_error(ec, "condition_variable timed_wait failed");
76 void
77 notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk)
79 auto& tl_ptr = __thread_local_data();
80 // If this thread was not created using std::thread then it will not have
81 // previously allocated.
82 if (tl_ptr.get() == nullptr) {
83 tl_ptr.set_pointer(new __thread_struct);
85 __thread_local_data()->notify_all_at_thread_exit(&cond, lk.release());
88 _LIBCPP_END_NAMESPACE_STD
90 _LIBCPP_POP_MACROS