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