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