1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // UNSUPPORTED: no-threads
10 // UNSUPPORTED: c++03, c++11
11 
12 // ALLOW_RETRIES: 2
13 
14 // shared_timed_mutex was introduced in macosx10.12
15 // UNSUPPORTED: use_system_cxx_lib && target={{.+}}-apple-macosx10.{{9|10|11}}
16 
17 // <shared_mutex>
18 
19 // class shared_timed_mutex;
20 
21 // bool try_lock_shared();
22 
23 #include <shared_mutex>
24 #include <thread>
25 #include <vector>
26 #include <cstdlib>
27 #include <cassert>
28 
29 #include "make_test_thread.h"
30 #include "test_macros.h"
31 
32 std::shared_timed_mutex m;
33 
34 typedef std::chrono::system_clock Clock;
35 typedef Clock::time_point time_point;
36 typedef Clock::duration duration;
37 typedef std::chrono::milliseconds ms;
38 typedef std::chrono::nanoseconds ns;
39 
40 
41 #if !defined(TEST_HAS_SANITIZERS)
42 ms Tolerance = ms(200);
43 #else
44 ms Tolerance = ms(200 * 5);
45 #endif
46 
f()47 void f()
48 {
49     time_point t0 = Clock::now();
50     assert(!m.try_lock_shared());
51     assert(!m.try_lock_shared());
52     assert(!m.try_lock_shared());
53     while(!m.try_lock_shared())
54         ;
55     time_point t1 = Clock::now();
56     m.unlock_shared();
57     ns d = t1 - t0 - ms(250);
58     assert(d < Tolerance);  // within tolerance
59 }
60 
main(int,char **)61 int main(int, char**)
62 {
63     m.lock();
64     std::vector<std::thread> v;
65     for (int i = 0; i < 5; ++i)
66         v.push_back(support::make_test_thread(f));
67     std::this_thread::sleep_for(ms(250));
68     m.unlock();
69     for (auto& t : v)
70         t.join();
71 
72   return 0;
73 }
74