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