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