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