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
10// UNSUPPORTED: no-threads
11
12// <mutex>
13
14// class mutex;
15
16// bool try_lock();
17
18#include <mutex>
19#include <cassert>
20#include <thread>
21
22#include "make_test_thread.h"
23
24int main(int, char**) {
25 // Try to lock a mutex that is not locked yet. This should succeed.
26 {
27 std::mutex m;
28 bool succeeded = m.try_lock();
29 assert(succeeded);
30 m.unlock();
31 }
32
33 // Try to lock a mutex that is already locked. This should fail.
34 {
35 std::mutex m;
36 m.lock();
37
38 std::thread t = support::make_test_thread([&] {
39 for (int i = 0; i != 10; ++i) {
40 bool succeeded = m.try_lock();
41 assert(!succeeded);
42 }
43 });
44 t.join();
45
46 m.unlock();
47 }
48
49 return 0;
50}
51

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