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 // <shared_mutex>
13 
14 // template <class Mutex> class shared_lock;
15 
16 // template <class Rep, class Period>
17 //   bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
18 
19 #include <shared_mutex>
20 #include <cassert>
21 #include <chrono>
22 #include <mutex>
23 
24 #include "test_macros.h"
25 
26 bool try_lock_for_called = false;
27 
28 typedef std::chrono::milliseconds ms;
29 
30 struct mutex
31 {
32     template <class Rep, class Period>
try_lock_shared_formutex33         bool try_lock_shared_for(const std::chrono::duration<Rep, Period>& rel_time)
34     {
35         assert(rel_time == ms(5));
36         try_lock_for_called = !try_lock_for_called;
37         return try_lock_for_called;
38     }
unlock_sharedmutex39     void unlock_shared() {}
40 };
41 
42 mutex m;
43 
main(int,char **)44 int main(int, char**)
45 {
46     std::shared_lock<mutex> lk(m, std::defer_lock);
47     assert(lk.try_lock_for(ms(5)) == true);
48     assert(try_lock_for_called == true);
49     assert(lk.owns_lock() == true);
50 #ifndef TEST_HAS_NO_EXCEPTIONS
51     try
52     {
53         TEST_IGNORE_NODISCARD lk.try_lock_for(ms(5));
54         assert(false);
55     }
56     catch (std::system_error& e)
57     {
58         assert(e.code().value() == EDEADLK);
59     }
60 #endif
61     lk.unlock();
62     assert(lk.try_lock_for(ms(5)) == false);
63     assert(try_lock_for_called == false);
64     assert(lk.owns_lock() == false);
65     lk.release();
66 #ifndef TEST_HAS_NO_EXCEPTIONS
67     try
68     {
69         TEST_IGNORE_NODISCARD lk.try_lock_for(ms(5));
70         assert(false);
71     }
72     catch (std::system_error& e)
73     {
74         assert(e.code().value() == EPERM);
75     }
76 #endif
77 
78   return 0;
79 }
80