Debian Codegraph @

libcxx/test/std/thread/thread.mutex/thread.lock/thread.lock.shared/thread.lock.shared.cons/mutex.pass.cpp

raw
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 // explicit shared_lock(mutex_type& m);
17
18 // template<class _Mutex> shared_lock(shared_lock<_Mutex>)
19 // -> shared_lock<_Mutex>; // C++17
20
21 #include <atomic>
22 #include <cassert>
23 #include <shared_mutex>
24 #include <thread>
25 #include <vector>
26
27 #include "make_test_thread.h"
28 #include "test_macros.h"
29
30 struct Monitor {
31 bool lock_shared_called = false;
32 bool unlock_shared_called = false;
33 };
34
35 struct TrackedMutex {
36 Monitor* monitor = nullptr;
37
38 void lock_shared() {
39 if (monitor != nullptr)
40 monitor->lock_shared_called = true;
41 }
42 void unlock_shared() {
43 if (monitor != nullptr)
44 monitor->unlock_shared_called = true;
45 }
46 };
47
48 template <class Mutex>
49 void test() {
50 // Basic sanity test
51 {
52 Mutex mutex;
53 std::vector<std::thread> threads;
54 std::atomic<bool> ready(false);
55 for (int i = 0; i != 5; ++i) {
56 threads.push_back(support::make_test_thread([&] {
57 while (!ready) {
58 // spin
59 }
60
61 std::shared_lock<Mutex> lock(mutex);
62 assert(lock.owns_lock());
63 }));
64 }
65
66 ready = true;
67 for (auto& t : threads)
68 t.join();
69 }
70
71 // Test CTAD
72 {
73 #if TEST_STD_VER >= 17
74 Mutex mutex;
75 std::shared_lock lock(mutex);
76 static_assert(std::is_same<decltype(lock), std::shared_lock<Mutex>>::value);
77 #endif
78 }
79 }
80
81 int main(int, char**) {
82 #if TEST_STD_VER >= 17
83 test<std::shared_mutex>();
84 #endif
85 test<std::shared_timed_mutex>();
86 test<TrackedMutex>();
87
88 // Use shared_lock with a dummy mutex class that tracks whether each
89 // operation has been called or not.
90 {
91 Monitor monitor;
92 TrackedMutex mutex{&monitor};
93
94 std::shared_lock<TrackedMutex> lock(mutex);
95 assert(monitor.lock_shared_called);
96 assert(lock.owns_lock());
97
98 lock.unlock();
99 assert(monitor.unlock_shared_called);
100 }
101
102 return 0;
103 }