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