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 // ALLOW_RETRIES: 2
12 
13 // <condition_variable>
14 
15 // class condition_variable_any;
16 
17 // template <class Lock, class Rep, class Period>
18 //   cv_status
19 //   wait_for(Lock& lock, const chrono::duration<Rep, Period>& rel_time);
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 std::condition_variable_any cv;
31 
32 typedef std::timed_mutex L0;
33 typedef std::unique_lock<L0> L1;
34 
35 L0 m0;
36 
37 int test1 = 0;
38 int test2 = 0;
39 
40 int runs = 0;
41 
42 void f()
43 {
44     typedef std::chrono::system_clock Clock;
45     typedef std::chrono::milliseconds milliseconds;
46     L1 lk(m0);
47     assert(test2 == 0);
48     test1 = 1;
49     cv.notify_one();
50     Clock::time_point t0 = Clock::now();
51     while (test2 == 0 &&
52            cv.wait_for(lk, milliseconds(250)) == std::cv_status::no_timeout)
53         ;
54     Clock::time_point t1 = Clock::now();
55     if (runs == 0)
56     {
57         assert(t1 - t0 < milliseconds(250));
58         assert(test2 != 0);
59     }
60     else
61     {
62         assert(t1 - t0 - milliseconds(250) < milliseconds(50));
63         assert(test2 == 0);
64     }
65     ++runs;
66 }
67 
68 int main(int, char**)
69 {
70     {
71         L1 lk(m0);
72         std::thread t = support::make_test_thread(f);
73         assert(test1 == 0);
74         while (test1 == 0)
75             cv.wait(lk);
76         assert(test1 != 0);
77         test2 = 1;
78         lk.unlock();
79         cv.notify_one();
80         t.join();
81     }
82     test1 = 0;
83     test2 = 0;
84     {
85         L1 lk(m0);
86         std::thread t = support::make_test_thread(f);
87         assert(test1 == 0);
88         while (test1 == 0)
89             cv.wait(lk);
90         assert(test1 != 0);
91         lk.unlock();
92         t.join();
93     }
94 
95   return 0;
96 }
97