blob: 4e0f19de07ce30c97df8a12863b741fd5fc8aa28 [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 Clock, class Duration>
18// bool try_lock_shared_until(const chrono::time_point<Clock, Duration>& abs_time);
19
20#include <shared_mutex>
21#include <thread>
22#include <vector>
23#include <cstdlib>
24#include <cassert>
25
David Majnemerf9f95be2014-03-17 20:19:44 +000026std::shared_timed_mutex m;
Howard Hinnantba898e42013-09-21 01:49:28 +000027
28typedef std::chrono::steady_clock Clock;
29typedef Clock::time_point time_point;
30typedef Clock::duration duration;
31typedef std::chrono::milliseconds ms;
32typedef std::chrono::nanoseconds ns;
33
34void f1()
35{
36 time_point t0 = Clock::now();
Dan Albert1d4a1ed2016-05-25 22:36:09 -070037 assert(m.try_lock_shared_until(Clock::now() + ms(300)) == true);
Howard Hinnantba898e42013-09-21 01:49:28 +000038 time_point t1 = Clock::now();
39 m.unlock_shared();
Dan Albert1d4a1ed2016-05-25 22:36:09 -070040 ns d = t1 - t0 - ms(250);
41 assert(d < ms(50)); // within 50ms
Howard Hinnantba898e42013-09-21 01:49:28 +000042}
43
44void f2()
45{
46 time_point t0 = Clock::now();
Dan Albert1d4a1ed2016-05-25 22:36:09 -070047 assert(m.try_lock_shared_until(Clock::now() + ms(250)) == false);
Howard Hinnantba898e42013-09-21 01:49:28 +000048 time_point t1 = Clock::now();
Dan Albert1d4a1ed2016-05-25 22:36:09 -070049 ns d = t1 - t0 - ms(250);
50 assert(d < ms(50)); // within 50ms
Howard Hinnantba898e42013-09-21 01:49:28 +000051}
52
Howard Hinnantba898e42013-09-21 01:49:28 +000053int main()
54{
Howard Hinnantba898e42013-09-21 01:49:28 +000055 {
56 m.lock();
57 std::vector<std::thread> v;
58 for (int i = 0; i < 5; ++i)
59 v.push_back(std::thread(f1));
Dan Albert1d4a1ed2016-05-25 22:36:09 -070060 std::this_thread::sleep_for(ms(250));
Howard Hinnantba898e42013-09-21 01:49:28 +000061 m.unlock();
62 for (auto& t : v)
63 t.join();
64 }
65 {
66 m.lock();
67 std::vector<std::thread> v;
68 for (int i = 0; i < 5; ++i)
69 v.push_back(std::thread(f2));
Dan Albert1d4a1ed2016-05-25 22:36:09 -070070 std::this_thread::sleep_for(ms(300));
Howard Hinnantba898e42013-09-21 01:49:28 +000071 m.unlock();
72 for (auto& t : v)
73 t.join();
74 }
Howard Hinnantba898e42013-09-21 01:49:28 +000075}