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