• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // <condition_variable>
13 
14 // class condition_variable_any;
15 
16 // template <class Lock, class Rep, class Period>
17 //   cv_status
18 //   wait_for(Lock& lock, const chrono::duration<Rep, Period>& rel_time);
19 
20 #include <condition_variable>
21 #include <mutex>
22 #include <thread>
23 #include <chrono>
24 #include <cassert>
25 
26 std::condition_variable_any cv;
27 
28 typedef std::timed_mutex L0;
29 typedef std::unique_lock<L0> L1;
30 
31 L0 m0;
32 
33 int test1 = 0;
34 int test2 = 0;
35 
36 int runs = 0;
37 
f()38 void f()
39 {
40     typedef std::chrono::system_clock Clock;
41     typedef std::chrono::milliseconds milliseconds;
42     L1 lk(m0);
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 
main()64 int main()
65 {
66     {
67         L1 lk(m0);
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         L1 lk(m0);
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