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: libcpp-has-no-threads
10 
11 // <mutex>
12 
13 // class recursive_mutex;
14 
15 // bool try_lock();
16 
17 #include <mutex>
18 #include <thread>
19 #include <cstdlib>
20 #include <cassert>
21 
22 #include "test_macros.h"
23 
24 std::recursive_mutex m;
25 
26 typedef std::chrono::system_clock Clock;
27 typedef Clock::time_point time_point;
28 typedef Clock::duration duration;
29 typedef std::chrono::milliseconds ms;
30 typedef std::chrono::nanoseconds ns;
31 
32 void f()
33 {
34     time_point t0 = Clock::now();
35     assert(!m.try_lock());
36     assert(!m.try_lock());
37     assert(!m.try_lock());
38     while(!m.try_lock())
39         ;
40     time_point t1 = Clock::now();
41     assert(m.try_lock());
42     m.unlock();
43     m.unlock();
44     ns d = t1 - t0 - ms(250);
45     assert(d < ms(200));  // within 200ms
46 }
47 
48 int main(int, char**)
49 {
50     m.lock();
51     std::thread t(f);
52     std::this_thread::sleep_for(ms(250));
53     m.unlock();
54     t.join();
55 
56   return 0;
57 }
58