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 // <mutex>
14 
15 // class timed_mutex;
16 
17 // template <class Rep, class Period>
18 //   unique_lock(mutex_type& m, const chrono::duration<Rep, Period>& rel_time);
19 
20 #include <mutex>
21 #include <thread>
22 #include <cstdlib>
23 #include <cassert>
24 
25 std::timed_mutex m;
26 
27 typedef std::chrono::steady_clock Clock;
28 typedef Clock::time_point time_point;
29 typedef Clock::duration duration;
30 typedef std::chrono::milliseconds ms;
31 typedef std::chrono::nanoseconds ns;
32 
33 void f1()
34 {
35     time_point t0 = Clock::now();
36     std::unique_lock<std::timed_mutex> lk(m, ms(300));
37     assert(lk.owns_lock() == true);
38     time_point t1 = Clock::now();
39     ns d = t1 - t0 - ms(250);
40     assert(d < ms(50));  // within 50ms
41 }
42 
43 void f2()
44 {
45     time_point t0 = Clock::now();
46     std::unique_lock<std::timed_mutex> lk(m, ms(250));
47     assert(lk.owns_lock() == false);
48     time_point t1 = Clock::now();
49     ns d = t1 - t0 - ms(250);
50     assert(d < ms(50));  // within 50ms
51 }
52 
53 int main(int, char**)
54 {
55     {
56         m.lock();
57         std::thread t(f1);
58         std::this_thread::sleep_for(ms(250));
59         m.unlock();
60         t.join();
61     }
62     {
63         m.lock();
64         std::thread t(f2);
65         std::this_thread::sleep_for(ms(300));
66         m.unlock();
67         t.join();
68     }
69 
70   return 0;
71 }
72