Debian Codegraph @

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