blob: 8fc6299f1b8f6b20d3e31b82004f968888c2c458 [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// void lock_shared();
18
19#include <shared_mutex>
20#include <thread>
21#include <vector>
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::system_clock Clock;
28typedef Clock::time_point time_point;
29typedef Clock::duration duration;
30typedef std::chrono::milliseconds ms;
31typedef std::chrono::nanoseconds ns;
32
33void f()
34{
35 time_point t0 = Clock::now();
36 m.lock_shared();
37 time_point t1 = Clock::now();
38 m.unlock_shared();
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 g()
44{
45 time_point t0 = Clock::now();
46 m.lock_shared();
47 time_point t1 = Clock::now();
48 m.unlock_shared();
49 ns d = t1 - t0;
Dan Albert1d4a1ed2016-05-25 22:36:09 -070050 assert(d < ms(50)); // within 50ms
Howard Hinnantba898e42013-09-21 01:49:28 +000051}
52
Howard Hinnantba898e42013-09-21 01:49:28 +000053
54int main()
55{
Howard Hinnantba898e42013-09-21 01:49:28 +000056 m.lock();
57 std::vector<std::thread> v;
58 for (int i = 0; i < 5; ++i)
59 v.push_back(std::thread(f));
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 m.lock_shared();
65 for (auto& t : v)
66 t = std::thread(g);
67 std::thread q(f);
Dan Albert1d4a1ed2016-05-25 22:36:09 -070068 std::this_thread::sleep_for(ms(250));
Howard Hinnantba898e42013-09-21 01:49:28 +000069 m.unlock_shared();
70 for (auto& t : v)
71 t.join();
72 q.join();
Howard Hinnantba898e42013-09-21 01:49:28 +000073}