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();
17
18#include <shared_mutex>
19#include <atomic>
20#include <cassert>
21#include <chrono>
22#include <thread>
23
24#include "make_test_thread.h"
25
26int main(int, char**) {
27 // Try to exclusive-lock a mutex that is not locked yet. This should succeed.
28 {
29 std::shared_mutex m;
30 bool succeeded = m.try_lock();
31 assert(succeeded);
32 m.unlock();
33 }
34
35 // Try to exclusive-lock a mutex that is already locked exclusively. This should fail.
36 {
37 std::shared_mutex m;
38 m.lock();
39
40 std::thread t = support::make_test_thread([&] {
41 bool succeeded = m.try_lock();
42 assert(!succeeded);
43 });
44 t.join();
45
46 m.unlock();
47 }
48
49 // Try to exclusive-lock a mutex that is already share-locked. This should fail.
50 {
51 std::shared_mutex m;
52 m.lock_shared();
53
54 std::thread t = support::make_test_thread([&] {
55 bool succeeded = m.try_lock();
56 assert(!succeeded);
57 });
58 t.join();
59
60 m.unlock_shared();
61 }
62
63 return 0;
64}
65

Provided by KDAB

Privacy Policy
Learn to use CMake with our Intro Training
Find out more

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