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_any;
14 
15 // template <class Lock, class Rep, class Period, class Predicate>
16 //   bool
17 //   wait_for(Lock& lock, const chrono::duration<Rep, Period>& rel_time,
18 //            Predicate pred);
19 
20 #include <condition_variable>
21 #include <mutex>
22 #include <thread>
23 #include <chrono>
24 #include <cassert>
25 
26 #include "test_macros.h"
27 
28 class Pred
29 {
30     int& i_;
31 public:
32     explicit Pred(int& i) : i_(i) {}
33 
34     bool operator()() {return i_ != 0;}
35 };
36 
37 std::condition_variable_any cv;
38 
39 typedef std::timed_mutex L0;
40 typedef std::unique_lock<L0> L1;
41 
42 L0 m0;
43 
44 int test1 = 0;
45 int test2 = 0;
46 
47 int runs = 0;
48 bool expect_result = false;
49 
50 void f()
51 {
52     typedef std::chrono::system_clock Clock;
53     typedef std::chrono::milliseconds milliseconds;
54     L1 lk(m0);
55     assert(test2 == 0);
56     test1 = 1;
57     cv.notify_one();
58     Clock::time_point t0 = Clock::now();
59     bool result = cv.wait_for(lk, milliseconds(250), Pred(test2));
60     assert(result == expect_result);
61     Clock::time_point t1 = Clock::now();
62     if (runs == 0)
63     {
64         assert(t1 - t0 < milliseconds(250));
65         assert(test2 != 0);
66     }
67     else
68     {
69         assert(t1 - t0 - milliseconds(250) < milliseconds(50));
70         assert(test2 == 0);
71     }
72     ++runs;
73 }
74 
75 int main(int, char**)
76 {
77     {
78         expect_result = true;
79         L1 lk(m0);
80         std::thread t(f);
81         assert(test1 == 0);
82         while (test1 == 0)
83             cv.wait(lk);
84         assert(test1 != 0);
85         test2 = 1;
86         lk.unlock();
87         cv.notify_one();
88         t.join();
89     }
90     test1 = 0;
91     test2 = 0;
92     {
93         expect_result = false;
94         L1 lk(m0);
95         std::thread t(f);
96         assert(test1 == 0);
97         while (test1 == 0)
98             cv.wait(lk);
99         assert(test1 != 0);
100         lk.unlock();
101         t.join();
102     }
103 
104   return 0;
105 }
106