1 //===----------------------------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is dual licensed under the MIT and the University of Illinois Open
6 // Source Licenses. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // <mutex>
11 
12 // template <class Mutex> class unique_lock;
13 
14 // unique_lock(mutex_type& m, try_to_lock_t);
15 
16 #include <mutex>
17 #include <thread>
18 #include <cstdlib>
19 #include <cassert>
20 
21 std::mutex m;
22 
23 typedef std::chrono::system_clock Clock;
24 typedef Clock::time_point time_point;
25 typedef Clock::duration duration;
26 typedef std::chrono::milliseconds ms;
27 typedef std::chrono::nanoseconds ns;
28 
29 void f()
30 {
31     time_point t0 = Clock::now();
32     {
33         std::unique_lock<std::mutex> lk(m, std::try_to_lock);
34         assert(lk.owns_lock() == false);
35     }
36     {
37         std::unique_lock<std::mutex> lk(m, std::try_to_lock);
38         assert(lk.owns_lock() == false);
39     }
40     {
41         std::unique_lock<std::mutex> lk(m, std::try_to_lock);
42         assert(lk.owns_lock() == false);
43     }
44     while (true)
45     {
46         std::unique_lock<std::mutex> lk(m, std::try_to_lock);
47         if (lk.owns_lock())
48             break;
49     }
50     time_point t1 = Clock::now();
51     ns d = t1 - t0 - ms(250);
52     assert(d < ms(200));  // within 200ms
53 }
54 
55 int main()
56 {
57     m.lock();
58     std::thread t(f);
59     std::this_thread::sleep_for(ms(250));
60     m.unlock();
61     t.join();
62 }
63