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 // ALLOW_RETRIES: 2
11 
12 // <mutex>
13 
14 // template <class Mutex> class unique_lock;
15 
16 // void lock();
17 
18 #include <mutex>
19 #include <thread>
20 #include <cstdlib>
21 #include <cassert>
22 
23 #include "make_test_thread.h"
24 #include "test_macros.h"
25 
26 std::mutex m;
27 
28 typedef std::chrono::system_clock Clock;
29 typedef Clock::time_point time_point;
30 typedef Clock::duration duration;
31 typedef std::chrono::milliseconds ms;
32 typedef std::chrono::nanoseconds ns;
33 
34 void f()
35 {
36     std::unique_lock<std::mutex> lk(m, std::defer_lock);
37     time_point t0 = Clock::now();
38     lk.lock();
39     time_point t1 = Clock::now();
40     assert(lk.owns_lock() == true);
41     ns d = t1 - t0 - ms(250);
42     assert(d < ms(25));  // within 25ms
43 #ifndef TEST_HAS_NO_EXCEPTIONS
44     try
45     {
46         lk.lock();
47         assert(false);
48     }
49     catch (std::system_error& e)
50     {
51         assert(e.code().value() == EDEADLK);
52     }
53 #endif
54     lk.unlock();
55     lk.release();
56 #ifndef TEST_HAS_NO_EXCEPTIONS
57     try
58     {
59         lk.lock();
60         assert(false);
61     }
62     catch (std::system_error& e)
63     {
64         assert(e.code().value() == EPERM);
65     }
66 #endif
67 }
68 
69 int main(int, char**)
70 {
71     m.lock();
72     std::thread t = support::make_test_thread(f);
73     std::this_thread::sleep_for(ms(250));
74     m.unlock();
75     t.join();
76 
77   return 0;
78 }
79