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 // <shared_mutex>
11 
12 // class shared_mutex;
13 
14 // template <class Rep, class Period>
15 //     bool try_lock_shared_for(const chrono::duration<Rep, Period>& rel_time);
16 
17 #include <shared_mutex>
18 #include <thread>
19 #include <vector>
20 #include <cstdlib>
21 #include <cassert>
22 
23 #if _LIBCPP_STD_VER > 11
24 
25 std::shared_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_shared_for(ms(300)) == true);
37     time_point t1 = Clock::now();
38     m.unlock_shared();
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_shared_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 
52 #endif  // _LIBCPP_STD_VER > 11
53 
main()54 int main()
55 {
56 #if _LIBCPP_STD_VER > 11
57     {
58         m.lock();
59         std::vector<std::thread> v;
60         for (int i = 0; i < 5; ++i)
61             v.push_back(std::thread(f1));
62         std::this_thread::sleep_for(ms(250));
63         m.unlock();
64         for (auto& t : v)
65             t.join();
66     }
67     {
68         m.lock();
69         std::vector<std::thread> v;
70         for (int i = 0; i < 5; ++i)
71             v.push_back(std::thread(f2));
72         std::this_thread::sleep_for(ms(300));
73         m.unlock();
74         for (auto& t : v)
75             t.join();
76     }
77 #endif  // _LIBCPP_STD_VER > 11
78 }
79