blob: ab20241895ba484e3ab970663bc845b160a46dfc [file] [log] [blame]
Howard Hinnantba898e42013-09-21 01:49:28 +00001//===----------------------------------------------------------------------===//
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//===----------------------------------------------------------------------===//
Jonathan Roelofs8d86b2e2014-09-05 19:45:05 +00009//
10// UNSUPPORTED: libcpp-has-no-threads
Marshall Clowf54ca462015-06-11 21:47:39 +000011// UNSUPPORTED: c++03, c++98, c++11
Howard Hinnantba898e42013-09-21 01:49:28 +000012
13// <shared_mutex>
14
David Majnemerf9f95be2014-03-17 20:19:44 +000015// class shared_timed_mutex;
Howard Hinnantba898e42013-09-21 01:49:28 +000016
17// template <class Rep, class Period>
18// bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
19
20#include <shared_mutex>
21#include <thread>
22#include <cstdlib>
23#include <cassert>
24
David Majnemerf9f95be2014-03-17 20:19:44 +000025std::shared_timed_mutex m;
Howard Hinnantba898e42013-09-21 01:49:28 +000026
27typedef std::chrono::steady_clock Clock;
28typedef Clock::time_point time_point;
29typedef Clock::duration duration;
30typedef std::chrono::milliseconds ms;
31typedef std::chrono::nanoseconds ns;
32
33void f1()
34{
35 time_point t0 = Clock::now();
Dan Albert1d4a1ed2016-05-25 22:36:09 -070036 assert(m.try_lock_for(ms(300)) == true);
Howard Hinnantba898e42013-09-21 01:49:28 +000037 time_point t1 = Clock::now();
38 m.unlock();
Dan Albert1d4a1ed2016-05-25 22:36:09 -070039 ns d = t1 - t0 - ms(250);
40 assert(d < ms(50)); // within 50ms
Howard Hinnantba898e42013-09-21 01:49:28 +000041}
42
43void f2()
44{
45 time_point t0 = Clock::now();
Dan Albert1d4a1ed2016-05-25 22:36:09 -070046 assert(m.try_lock_for(ms(250)) == false);
Howard Hinnantba898e42013-09-21 01:49:28 +000047 time_point t1 = Clock::now();
Dan Albert1d4a1ed2016-05-25 22:36:09 -070048 ns d = t1 - t0 - ms(250);
49 assert(d < ms(50)); // within 50ms
Howard Hinnantba898e42013-09-21 01:49:28 +000050}
51
Howard Hinnantba898e42013-09-21 01:49:28 +000052int main()
53{
Howard Hinnantba898e42013-09-21 01:49:28 +000054 {
55 m.lock();
56 std::thread t(f1);
Dan Albert1d4a1ed2016-05-25 22:36:09 -070057 std::this_thread::sleep_for(ms(250));
Howard Hinnantba898e42013-09-21 01:49:28 +000058 m.unlock();
59 t.join();
60 }
61 {
62 m.lock();
63 std::thread t(f2);
Dan Albert1d4a1ed2016-05-25 22:36:09 -070064 std::this_thread::sleep_for(ms(300));
Howard Hinnantba898e42013-09-21 01:49:28 +000065 m.unlock();
66 t.join();
67 }
Howard Hinnantba898e42013-09-21 01:49:28 +000068}