blob: c8a0287314bfd9df98548e5c7d3f8a80e1df5b38 [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
Howard Hinnantba898e42013-09-21 01:49:28 +000011
12// <shared_mutex>
13
14// template <class Mutex> class shared_lock;
15
16// explicit shared_lock(mutex_type& m);
17
18#include <shared_mutex>
19#include <thread>
20#include <vector>
21#include <cstdlib>
22#include <cassert>
23
Dan Albert1d4a1ed2016-05-25 22:36:09 -070024#if _LIBCPP_STD_VER > 11
25
26std::shared_timed_mutex m;
Howard Hinnantba898e42013-09-21 01:49:28 +000027
28typedef std::chrono::system_clock Clock;
29typedef Clock::time_point time_point;
30typedef Clock::duration duration;
31typedef std::chrono::milliseconds ms;
32typedef std::chrono::nanoseconds ns;
33
34void f()
35{
36 time_point t0 = Clock::now();
37 time_point t1;
38 {
David Majnemerf9f95be2014-03-17 20:19:44 +000039 std::shared_lock<std::shared_timed_mutex> ul(m);
Howard Hinnantba898e42013-09-21 01:49:28 +000040 t1 = Clock::now();
41 }
Dan Albert1d4a1ed2016-05-25 22:36:09 -070042 ns d = t1 - t0 - ms(250);
43 assert(d < ms(50)); // within 50ms
Howard Hinnantba898e42013-09-21 01:49:28 +000044}
45
46void g()
47{
48 time_point t0 = Clock::now();
49 time_point t1;
50 {
David Majnemerf9f95be2014-03-17 20:19:44 +000051 std::shared_lock<std::shared_timed_mutex> ul(m);
Howard Hinnantba898e42013-09-21 01:49:28 +000052 t1 = Clock::now();
53 }
54 ns d = t1 - t0;
Dan Albert1d4a1ed2016-05-25 22:36:09 -070055 assert(d < ms(50)); // within 50ms
Howard Hinnantba898e42013-09-21 01:49:28 +000056}
57
Dan Albert1d4a1ed2016-05-25 22:36:09 -070058#endif // _LIBCPP_STD_VER > 11
59
Howard Hinnantba898e42013-09-21 01:49:28 +000060int main()
61{
Dan Albert1d4a1ed2016-05-25 22:36:09 -070062#if _LIBCPP_STD_VER > 11
63 m.lock();
Howard Hinnantba898e42013-09-21 01:49:28 +000064 std::vector<std::thread> v;
Dan Albert1d4a1ed2016-05-25 22:36:09 -070065 for (int i = 0; i < 5; ++i)
66 v.push_back(std::thread(f));
67 std::this_thread::sleep_for(ms(250));
68 m.unlock();
69 for (auto& t : v)
70 t.join();
71 m.lock_shared();
72 for (auto& t : v)
73 t = std::thread(g);
74 std::thread q(f);
75 std::this_thread::sleep_for(ms(250));
76 m.unlock_shared();
77 for (auto& t : v)
78 t.join();
79 q.join();
80#endif // _LIBCPP_STD_VER > 11
Howard Hinnantba898e42013-09-21 01:49:28 +000081}