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// class timed_mutex;
13
14// template <class Clock, class Duration>
15//     bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time);
16
17#include <mutex>
18#include <thread>
19#include <cstdlib>
20#include <cassert>
21
22std::timed_mutex m;
23
24typedef std::chrono::steady_clock Clock;
25typedef Clock::time_point time_point;
26typedef Clock::duration duration;
27typedef std::chrono::milliseconds ms;
28typedef std::chrono::nanoseconds ns;
29
30void f1()
31{
32    time_point t0 = Clock::now();
33    assert(m.try_lock_until(Clock::now() + ms(300)) == true);
34    time_point t1 = Clock::now();
35    m.unlock();
36    ns d = t1 - t0 - ms(250);
37    assert(d < ms(50));  // within 50ms
38}
39
40void f2()
41{
42    time_point t0 = Clock::now();
43    assert(m.try_lock_until(Clock::now() + ms(250)) == false);
44    time_point t1 = Clock::now();
45    ns d = t1 - t0 - ms(250);
46    assert(d < ms(50));  // within 50ms
47}
48
49int main()
50{
51    {
52        m.lock();
53        std::thread t(f1);
54        std::this_thread::sleep_for(ms(250));
55        m.unlock();
56        t.join();
57    }
58    {
59        m.lock();
60        std::thread t(f2);
61        std::this_thread::sleep_for(ms(300));
62        m.unlock();
63        t.join();
64    }
65}
66