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 #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 cv;
39 std::mutex mut;
40 
41 int test1 = 0;
42 int test2 = 0;
43 
44 int runs = 0;
45 
46 void f()
47 {
48     typedef std::chrono::system_clock Clock;
49     typedef std::chrono::milliseconds milliseconds;
50     std::unique_lock<std::mutex> lk(mut);
51     assert(test2 == 0);
52     test1 = 1;
53     cv.notify_one();
54     Clock::time_point t0 = Clock::now();
55     bool r = cv.wait_for(lk, milliseconds(250), Pred(test2));
56     ((void)r); // Prevent unused warning
57     Clock::time_point t1 = Clock::now();
58     if (runs == 0)
59     {
60         assert(t1 - t0 < milliseconds(250));
61         assert(test2 != 0);
62     }
63     else
64     {
65         assert(t1 - t0 - milliseconds(250) < milliseconds(50));
66         assert(test2 == 0);
67     }
68     ++runs;
69 }
70 
71 int main(int, char**)
72 {
73     {
74         std::unique_lock<std::mutex>lk(mut);
75         std::thread t(f);
76         assert(test1 == 0);
77         while (test1 == 0)
78             cv.wait(lk);
79         assert(test1 != 0);
80         test2 = 1;
81         lk.unlock();
82         cv.notify_one();
83         t.join();
84     }
85     test1 = 0;
86     test2 = 0;
87     {
88         std::unique_lock<std::mutex>lk(mut);
89         std::thread t(f);
90         assert(test1 == 0);
91         while (test1 == 0)
92             cv.wait(lk);
93         assert(test1 != 0);
94         lk.unlock();
95         t.join();
96     }
97 
98   return 0;
99 }
100