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 // UNSUPPORTED: c++03, c++98, c++11
12 
13 // <shared_mutex>
14 
15 // class shared_timed_mutex;
16 
17 // template <class Rep, class Period>
18 //     bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
19 
20 #include <shared_mutex>
21 #include <thread>
22 #include <cstdlib>
23 #include <cassert>
24 
25 std::shared_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 
f1()33 void f1()
34 {
35     time_point t0 = Clock::now();
36     assert(m.try_lock_for(ms(300)) == true);
37     time_point t1 = Clock::now();
38     m.unlock();
39     ns d = t1 - t0 - ms(250);
40     assert(d < ms(50));  // within 50ms
41 }
42 
f2()43 void f2()
44 {
45     time_point t0 = Clock::now();
46     assert(m.try_lock_for(ms(250)) == false);
47     time_point t1 = Clock::now();
48     ns d = t1 - t0 - ms(250);
49     assert(d < ms(50));  // within 50ms
50 }
51 
main()52 int main()
53 {
54     {
55         m.lock();
56         std::thread t(f1);
57         std::this_thread::sleep_for(ms(250));
58         m.unlock();
59         t.join();
60     }
61     {
62         m.lock();
63         std::thread t(f2);
64         std::this_thread::sleep_for(ms(300));
65         m.unlock();
66         t.join();
67     }
68 }
69