1 //===----------------------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // UNSUPPORTED: no-threads
10 // UNSUPPORTED: c++03, c++11
14 // template <class Mutex> class shared_lock;
20 #include <mutex> // std::defer_lock
21 #include <shared_mutex>
22 #include <system_error>
26 #include "make_test_thread.h"
27 #include "test_macros.h"
30 bool lock_shared_called = false;
31 bool unlock_shared_called = false;
35 Monitor* monitor = nullptr;
38 if (monitor != nullptr)
39 monitor->lock_shared_called = true;
41 void unlock_shared() {
42 if (monitor != nullptr)
43 monitor->unlock_shared_called = true;
47 template <class Mutex>
52 std::vector<std::thread> threads;
53 std::atomic<bool> ready(false);
54 for (int i = 0; i != 5; ++i) {
55 threads.push_back(support::make_test_thread([&] {
60 std::shared_lock<Mutex> lock(mutex, std::defer_lock);
62 assert(lock.owns_lock());
67 for (auto& t : threads)
71 // Try locking the same shared_lock again in the same thread. This should throw an exception.
74 std::shared_lock<Mutex> lock(mutex, std::defer_lock);
76 assert(lock.owns_lock());
77 #ifndef TEST_HAS_NO_EXCEPTIONS
81 } catch (std::system_error const& e) {
82 assert(e.code() == std::errc::resource_deadlock_would_occur);
87 // Try locking a shared_lock that isn't associated to any mutex. This should throw an exception.
89 std::shared_lock<Mutex> lock; // no associated mutex
90 #ifndef TEST_HAS_NO_EXCEPTIONS
94 } catch (std::system_error const& e) {
95 assert(e.code() == std::errc::operation_not_permitted);
101 int main(int, char**) {
102 #if TEST_STD_VER >= 17
103 test<std::shared_mutex>();
105 test<std::shared_timed_mutex>();
106 test<TrackedMutex>();
108 // Use shared_lock with a dummy mutex class that tracks whether each
109 // operation has been called or not.
112 TrackedMutex mutex{&monitor};
114 std::shared_lock<TrackedMutex> lock(mutex, std::defer_lock);
116 assert(monitor.lock_shared_called);
117 assert(lock.owns_lock());
120 assert(monitor.unlock_shared_called);