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++98, c++03, c++11
12 
13 // <shared_mutex>
14 
15 // template <class Mutex> class shared_lock;
16 
17 // explicit shared_lock(mutex_type& m);
18 
19 #include <shared_mutex>
20 #include <thread>
21 #include <vector>
22 #include <cstdlib>
23 #include <cassert>
24 
25 #include "test_macros.h"
26 
27 typedef std::chrono::system_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 
33 ms WaitTime = ms(250);
34 
35 // Thread sanitizer causes more overhead and will sometimes cause this test
36 // to fail. To prevent this we give Thread sanitizer more time to complete the
37 // test.
38 #if !TEST_HAS_FEATURE(thread_sanitizer)
39 ms Tolerance = ms(50);
40 #else
41 ms Tolerance = ms(100);
42 #endif
43 
44 std::shared_timed_mutex m;
45 
46 void f()
47 {
48     time_point t0 = Clock::now();
49     time_point t1;
50     {
51     std::shared_lock<std::shared_timed_mutex> ul(m);
52     t1 = Clock::now();
53     }
54     ns d = t1 - t0 - WaitTime;
55     assert(d < Tolerance);  // within tolerance
56 }
57 
58 void g()
59 {
60     time_point t0 = Clock::now();
61     time_point t1;
62     {
63     std::shared_lock<std::shared_timed_mutex> ul(m);
64     t1 = Clock::now();
65     }
66     ns d = t1 - t0;
67     assert(d < Tolerance);  // within tolerance
68 }
69 
70 int main()
71 {
72     std::vector<std::thread> v;
73     {
74         m.lock();
75         for (int i = 0; i < 5; ++i)
76             v.push_back(std::thread(f));
77         std::this_thread::sleep_for(WaitTime);
78         m.unlock();
79         for (auto& t : v)
80             t.join();
81     }
82     {
83         m.lock_shared();
84         for (auto& t : v)
85             t = std::thread(g);
86         std::thread q(f);
87         std::this_thread::sleep_for(WaitTime);
88         m.unlock_shared();
89         for (auto& t : v)
90             t.join();
91         q.join();
92     }
93 }
94