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 // <shared_mutex>
13 
14 // class timed_mutex;
15 
16 // template <class Rep, class Period>
17 //   shared_lock(mutex_type& m, const chrono::duration<Rep, Period>& rel_time);
18 
19 #include <shared_mutex>
20 #include <thread>
21 #include <vector>
22 #include <cstdlib>
23 #include <cassert>
24 
25 #if _LIBCPP_STD_VER > 11
26 
27 std::shared_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::shared_lock<std::shared_timed_mutex> lk(m, ms(300));
39     assert(lk.owns_lock() == true);
40     time_point t1 = Clock::now();
41     ns d = t1 - t0 - ms(250);
42     assert(d < ms(50));  // within 50ms
43 }
44 
f2()45 void f2()
46 {
47     time_point t0 = Clock::now();
48     std::shared_lock<std::shared_timed_mutex> lk(m, 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 
55 #endif  // _LIBCPP_STD_VER > 11
56 
main()57 int main()
58 {
59 #if _LIBCPP_STD_VER > 11
60     {
61         m.lock();
62         std::vector<std::thread> v;
63         for (int i = 0; i < 5; ++i)
64             v.push_back(std::thread(f1));
65         std::this_thread::sleep_for(ms(250));
66         m.unlock();
67         for (auto& t : v)
68             t.join();
69     }
70     {
71         m.lock();
72         std::vector<std::thread> v;
73         for (int i = 0; i < 5; ++i)
74             v.push_back(std::thread(f2));
75         std::this_thread::sleep_for(ms(300));
76         m.unlock();
77         for (auto& t : v)
78             t.join();
79     }
80 #endif  // _LIBCPP_STD_VER > 11
81 }
82