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