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: libcpp-has-no-threads
10 // UNSUPPORTED: c++98, c++03, c++11
11 //
12 // ALLOW_RETRIES: 2
13 
14 // <shared_mutex>
15 
16 // template <class Mutex> class shared_lock;
17 
18 // bool try_lock();
19 
20 #include <shared_mutex>
21 #include <cassert>
22 
23 #include "test_macros.h"
24 
25 bool try_lock_called = false;
26 
27 struct mutex
28 {
29     bool try_lock_shared()
30     {
31         try_lock_called = !try_lock_called;
32         return try_lock_called;
33     }
34     void unlock_shared() {}
35 };
36 
37 mutex m;
38 
39 int main(int, char**)
40 {
41     std::shared_lock<mutex> lk(m, std::defer_lock);
42     assert(lk.try_lock() == true);
43     assert(try_lock_called == true);
44     assert(lk.owns_lock() == true);
45 #ifndef TEST_HAS_NO_EXCEPTIONS
46     try
47     {
48         TEST_IGNORE_NODISCARD lk.try_lock();
49         assert(false);
50     }
51     catch (std::system_error& e)
52     {
53         assert(e.code().value() == EDEADLK);
54     }
55 #endif
56     lk.unlock();
57     assert(lk.try_lock() == false);
58     assert(try_lock_called == false);
59     assert(lk.owns_lock() == false);
60     lk.release();
61 #ifndef TEST_HAS_NO_EXCEPTIONS
62     try
63     {
64         TEST_IGNORE_NODISCARD lk.try_lock();
65         assert(false);
66     }
67     catch (std::system_error& e)
68     {
69         assert(e.code().value() == EPERM);
70     }
71 #endif
72 
73   return 0;
74 }
75