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 // <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 #include "make_test_thread.h"
26 #include "test_macros.h"
27 
28 std::timed_mutex m;
29 
30 typedef std::chrono::steady_clock Clock;
31 typedef Clock::time_point time_point;
32 typedef Clock::duration duration;
33 typedef std::chrono::milliseconds ms;
34 typedef std::chrono::nanoseconds ns;
35 
36 void f1()
37 {
38     time_point t0 = Clock::now();
39     std::unique_lock<std::timed_mutex> lk(m, ms(300));
40     assert(lk.owns_lock() == true);
41     time_point t1 = Clock::now();
42     ns d = t1 - t0 - ms(250);
43     assert(d < ms(50));  // within 50ms
44 }
45 
46 void f2()
47 {
48     time_point t0 = Clock::now();
49     std::unique_lock<std::timed_mutex> lk(m, ms(250));
50     assert(lk.owns_lock() == false);
51     time_point t1 = Clock::now();
52     ns d = t1 - t0 - ms(250);
53     assert(d < ms(50));  // within 50ms
54 }
55 
56 int main(int, char**)
57 {
58     {
59         m.lock();
60         std::thread t = support::make_test_thread(f1);
61         std::this_thread::sleep_for(ms(250));
62         m.unlock();
63         t.join();
64     }
65     {
66         m.lock();
67         std::thread t = support::make_test_thread(f2);
68         std::this_thread::sleep_for(ms(300));
69         m.unlock();
70         t.join();
71     }
72 
73   return 0;
74 }
75