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