1 //===----------------------------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // UNSUPPORTED: libcpp-has-no-threads
11 
12 // FLAKY_TEST
13 
14 // <condition_variable>
15 
16 // class condition_variable;
17 
18 // template <class Rep, class Period>
19 //     cv_status
20 //     wait_for(unique_lock<mutex>& lock,
21 //              const chrono::duration<Rep, Period>& rel_time);
22 
23 #include <condition_variable>
24 #include <mutex>
25 #include <thread>
26 #include <chrono>
27 #include <cassert>
28 
29 std::condition_variable cv;
30 std::mutex mut;
31 
32 int test1 = 0;
33 int test2 = 0;
34 
35 int runs = 0;
36 
f()37 void f()
38 {
39     typedef std::chrono::system_clock Clock;
40     typedef std::chrono::milliseconds milliseconds;
41     std::unique_lock<std::mutex> lk(mut);
42     assert(test2 == 0);
43     test1 = 1;
44     cv.notify_one();
45     Clock::time_point t0 = Clock::now();
46     while (test2 == 0 &&
47            cv.wait_for(lk, milliseconds(250)) == std::cv_status::no_timeout)
48         ;
49     Clock::time_point t1 = Clock::now();
50     if (runs == 0)
51     {
52         assert(t1 - t0 < milliseconds(250));
53         assert(test2 != 0);
54     }
55     else
56     {
57         assert(t1 - t0 - milliseconds(250) < milliseconds(50));
58         assert(test2 == 0);
59     }
60     ++runs;
61 }
62 
main()63 int main()
64 {
65     {
66         std::unique_lock<std::mutex>lk(mut);
67         std::thread t(f);
68         assert(test1 == 0);
69         while (test1 == 0)
70             cv.wait(lk);
71         assert(test1 != 0);
72         test2 = 1;
73         lk.unlock();
74         cv.notify_one();
75         t.join();
76     }
77     test1 = 0;
78     test2 = 0;
79     {
80         std::unique_lock<std::mutex>lk(mut);
81         std::thread t(f);
82         assert(test1 == 0);
83         while (test1 == 0)
84             cv.wait(lk);
85         assert(test1 != 0);
86         lk.unlock();
87         t.join();
88     }
89 }
90