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: c++03, c++11, c++14
10 // UNSUPPORTED: no-threads
11 // REQUIRES: thread-safety
12 // ADDITIONAL_COMPILE_FLAGS: -D_LIBCPP_ENABLE_THREAD_SAFETY_ANNOTATIONS
13
14 // On Windows Clang bugs out when both __declspec and __attribute__ are present,
15 // the processing goes awry preventing the definition of the types.
16 // XFAIL: msvc
17
18 // <shared_mutex>
19 //
20 // class shared_mutex;
21 //
22 // void lock();
23 // bool try_lock();
24 // void unlock();
25 //
26 // void lock_shared();
27 // bool try_lock_shared();
28 // void unlock_shared();
29
30 #include <shared_mutex>
31
32 std::shared_mutex m;
33 int data __attribute__((guarded_by(m))) = 0;
34 void read(int);
35
f()36 void f() {
37 // Exclusive locking
38 {
39 m.lock();
40 ++data; // ok
41 m.unlock();
42 }
43 {
44 if (m.try_lock()) {
45 ++data; // ok
46 m.unlock();
47 }
48 }
49
50 // Shared locking
51 {
52 m.lock_shared();
53 read(data); // ok
54 ++data; // expected-error {{writing variable 'data' requires holding shared_mutex 'm' exclusively}}
55 m.unlock_shared();
56 }
57 {
58 if (m.try_lock_shared()) {
59 read(data); // ok
60 ++data; // expected-error {{writing variable 'data' requires holding shared_mutex 'm' exclusively}}
61 m.unlock_shared();
62 }
63 }
64 }
65