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, c++14
11
12// <shared_mutex>
13
14// class shared_mutex;
15
16// bool try_lock_shared();
17
18#include <shared_mutex>
19#include <cassert>
20#include <thread>
21#include <vector>
22
23#include "make_test_thread.h"
24
25int main(int, char**) {
26 // Try to lock-shared a mutex that is not locked yet. This should succeed.
27 {
28 std::shared_mutex m;
29 std::vector<std::thread> threads;
30 for (int i = 0; i != 5; ++i) {
31 threads.push_back(support::make_test_thread([&] {
32 bool succeeded = m.try_lock_shared();
33 assert(succeeded);
34 m.unlock_shared();
35 }));
36 }
37
38 for (auto& t : threads)
39 t.join();
40 }
41
42 // Try to lock-shared a mutex that is already exclusively locked. This should fail.
43 {
44 std::shared_mutex m;
45 m.lock();
46
47 std::vector<std::thread> threads;
48 for (int i = 0; i != 5; ++i) {
49 threads.push_back(support::make_test_thread([&] {
50 bool succeeded = m.try_lock_shared();
51 assert(!succeeded);
52 }));
53 }
54
55 for (auto& t : threads)
56 t.join();
57
58 m.unlock();
59 }
60
61 // Try to lock-shared a mutex that is already lock-shared. This should succeed.
62 {
63 std::shared_mutex m;
64 m.lock_shared();
65 std::vector<std::thread> threads;
66 for (int i = 0; i != 5; ++i) {
67 threads.push_back(support::make_test_thread([&] {
68 bool succeeded = m.try_lock_shared();
69 assert(succeeded);
70 m.unlock_shared();
71 }));
72 }
73 m.unlock_shared();
74
75 for (auto& t : threads)
76 t.join();
77 }
78
79 return 0;
80}
81

source code of libcxx/test/std/thread/thread.mutex/thread.mutex.requirements/thread.shared_mutex.requirements/thread.shared_mutex.class/try_lock_shared.pass.cpp