Debian Codegraph @

libcxx/test/std/thread/thread.mutex/thread.lock/thread.lock.unique/thread.lock.unique.locking/try_lock.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
11 // ALLOW_RETRIES: 2
12
13 // <mutex>
14
15 // template <class Mutex> class unique_lock;
16
17 // bool try_lock();
18
19 #include <cassert>
20 #include <mutex>
21 #include <system_error>
22
23 #include "test_macros.h"
24
25 bool try_lock_called = false;
26
27 struct mutex
28 {
29 bool try_lock()
30 {
31 try_lock_called = !try_lock_called;
32 return try_lock_called;
33 }
34 void unlock() {}
35 };
36
37 mutex m;
38
39 int main(int, char**)
40 {
41 std::unique_lock<mutex> lk(m, std::defer_lock);
42 assert(lk.try_lock() == true);
43 assert(try_lock_called == true);
44 assert(lk.owns_lock() == true);
45 #ifndef TEST_HAS_NO_EXCEPTIONS
46 try
47 {
48 TEST_IGNORE_NODISCARD lk.try_lock();
49 assert(false);
50 }
51 catch (std::system_error& e)
52 {
53 assert(e.code().value() == EDEADLK);
54 }
55 #endif
56 lk.unlock();
57 assert(lk.try_lock() == false);
58 assert(try_lock_called == false);
59 assert(lk.owns_lock() == false);
60 lk.release();
61 #ifndef TEST_HAS_NO_EXCEPTIONS
62 try
63 {
64 TEST_IGNORE_NODISCARD lk.try_lock();
65 assert(false);
66 }
67 catch (std::system_error& e)
68 {
69 assert(e.code().value() == EPERM);
70 }
71 #endif
72
73 return 0;
74 }