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 // UNSUPPORTED: libcpp-has-no-threads
10 
11 // <condition_variable>
12 
13 // class condition_variable;
14 
15 // template <class Clock, class Duration>
16 //   cv_status
17 //   wait_until(unique_lock<mutex>& lock,
18 //              const chrono::time_point<Clock, Duration>& abs_time);
19 
20 #include <condition_variable>
21 #include <mutex>
22 #include <thread>
23 #include <chrono>
24 #include <cassert>
25 
26 struct Clock
27 {
28     typedef std::chrono::milliseconds duration;
29     typedef duration::rep             rep;
30     typedef duration::period          period;
31     typedef std::chrono::time_point<Clock> time_point;
32     static const bool is_steady =  true;
33 
34     static time_point now()
35     {
36         using namespace std::chrono;
37         return time_point(duration_cast<duration>(
38                 steady_clock::now().time_since_epoch()
39                                                  ));
40     }
41 };
42 
43 std::condition_variable cv;
44 std::mutex mut;
45 
46 int test1 = 0;
47 int test2 = 0;
48 
49 int runs = 0;
50 
51 void f()
52 {
53     std::unique_lock<std::mutex> lk(mut);
54     assert(test2 == 0);
55     test1 = 1;
56     cv.notify_one();
57     Clock::time_point t0 = Clock::now();
58     Clock::time_point t = t0 + Clock::duration(250);
59     while (test2 == 0 && cv.wait_until(lk, t) == std::cv_status::no_timeout)
60         ;
61     Clock::time_point t1 = Clock::now();
62     if (runs == 0)
63     {
64         assert(t1 - t0 < Clock::duration(250));
65         assert(test2 != 0);
66     }
67     else
68     {
69         assert(t1 - t0 - Clock::duration(250) < Clock::duration(50));
70         assert(test2 == 0);
71     }
72     ++runs;
73 }
74 
75 int main(int, char**)
76 {
77     {
78         std::unique_lock<std::mutex>lk(mut);
79         std::thread t(f);
80         assert(test1 == 0);
81         while (test1 == 0)
82             cv.wait(lk);
83         assert(test1 != 0);
84         test2 = 1;
85         lk.unlock();
86         cv.notify_one();
87         t.join();
88     }
89     test1 = 0;
90     test2 = 0;
91     {
92         std::unique_lock<std::mutex>lk(mut);
93         std::thread t(f);
94         assert(test1 == 0);
95         while (test1 == 0)
96             cv.wait(lk);
97         assert(test1 != 0);
98         lk.unlock();
99         t.join();
100     }
101 
102   return 0;
103 }
104