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 // ALLOW_RETRIES: 2
12 
13 // dylib support for shared_mutex was added in macosx10.12
14 // XFAIL: use_system_cxx_lib && target={{.+}}-apple-macosx10.{{9|10|11}}
15 
16 // <shared_mutex>
17 
18 // template <class Mutex> class shared_lock;
19 
20 // shared_lock(mutex_type& m, try_to_lock_t);
21 
22 #include <shared_mutex>
23 #include <thread>
24 #include <vector>
25 #include <cstdlib>
26 #include <cassert>
27 
28 #include "make_test_thread.h"
29 #include "test_macros.h"
30 
31 std::shared_timed_mutex m;
32 
33 typedef std::chrono::system_clock Clock;
34 typedef Clock::time_point time_point;
35 typedef Clock::duration duration;
36 typedef std::chrono::milliseconds ms;
37 typedef std::chrono::nanoseconds ns;
38 
f()39 void f()
40 {
41     time_point t0 = Clock::now();
42     {
43         std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
44         assert(lk.owns_lock() == false);
45     }
46     {
47         std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
48         assert(lk.owns_lock() == false);
49     }
50     {
51         std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
52         assert(lk.owns_lock() == false);
53     }
54     while (true)
55     {
56         std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
57         if (lk.owns_lock())
58             break;
59     }
60     time_point t1 = Clock::now();
61     ns d = t1 - t0 - ms(250);
62     assert(d < ms(200));  // within 200ms
63 }
64 
main(int,char **)65 int main(int, char**)
66 {
67     m.lock();
68     std::vector<std::thread> v;
69     for (int i = 0; i < 5; ++i)
70         v.push_back(support::make_test_thread(f));
71     std::this_thread::sleep_for(ms(250));
72     m.unlock();
73     for (auto& t : v)
74         t.join();
75 
76   return 0;
77 }
78