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 Rep, class Period>
15//   unique_lock(mutex_type& m, const chrono::duration<Rep, Period>& rel_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    std::unique_lock<std::timed_mutex> lk(m, ms(300));
34    assert(lk.owns_lock() == true);
35    time_point t1 = Clock::now();
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    std::unique_lock<std::timed_mutex> lk(m, ms(250));
44    assert(lk.owns_lock() == false);
45    time_point t1 = Clock::now();
46    ns d = t1 - t0 - ms(250);
47    assert(d < ms(50));  // within 50ms
48}
49
50int main()
51{
52    {
53        m.lock();
54        std::thread t(f1);
55        std::this_thread::sleep_for(ms(250));
56        m.unlock();
57        t.join();
58    }
59    {
60        m.lock();
61        std::thread t(f2);
62        std::this_thread::sleep_for(ms(300));
63        m.unlock();
64        t.join();
65    }
66}
67