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