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 // unique_lock(mutex_type& m, try_to_lock_t);
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 
f()34 void f()
35 {
36     time_point t0 = Clock::now();
37     {
38         std::unique_lock<std::mutex> lk(m, std::try_to_lock);
39         assert(lk.owns_lock() == false);
40     }
41     {
42         std::unique_lock<std::mutex> lk(m, std::try_to_lock);
43         assert(lk.owns_lock() == false);
44     }
45     {
46         std::unique_lock<std::mutex> lk(m, std::try_to_lock);
47         assert(lk.owns_lock() == false);
48     }
49     while (true)
50     {
51         std::unique_lock<std::mutex> lk(m, std::try_to_lock);
52         if (lk.owns_lock())
53             break;
54     }
55     time_point t1 = Clock::now();
56     ns d = t1 - t0 - ms(250);
57     assert(d < ms(200));  // within 200ms
58 }
59 
main(int,char **)60 int main(int, char**)
61 {
62     m.lock();
63     std::thread t = support::make_test_thread(f);
64     std::this_thread::sleep_for(ms(250));
65     m.unlock();
66     t.join();
67 
68   return 0;
69 }
70