blob: f2d4e0deb73f355037e48ca412f27ab792e8606f [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// shared_lock(mutex_type& m, try_to_lock_t);
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
David Majnemerf9f95be2014-03-17 20:19:44 +000026std::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 {
David Majnemerf9f95be2014-03-17 20:19:44 +000038 std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
Howard Hinnantba898e42013-09-21 01:49:28 +000039 assert(lk.owns_lock() == false);
40 }
41 {
David Majnemerf9f95be2014-03-17 20:19:44 +000042 std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
Howard Hinnantba898e42013-09-21 01:49:28 +000043 assert(lk.owns_lock() == false);
44 }
45 {
David Majnemerf9f95be2014-03-17 20:19:44 +000046 std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
Howard Hinnantba898e42013-09-21 01:49:28 +000047 assert(lk.owns_lock() == false);
48 }
49 while (true)
50 {
David Majnemerf9f95be2014-03-17 20:19:44 +000051 std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
Howard Hinnantba898e42013-09-21 01:49:28 +000052 if (lk.owns_lock())
53 break;
54 }
55 time_point t1 = Clock::now();
56 ns d = t1 - t0 - ms(250);
57 assert(d < ms(200)); // within 200ms
58}
59
Dan Albert1d4a1ed2016-05-25 22:36:09 -070060#endif // _LIBCPP_STD_VER > 11
61
Howard Hinnantba898e42013-09-21 01:49:28 +000062int main()
63{
Dan Albert1d4a1ed2016-05-25 22:36:09 -070064#if _LIBCPP_STD_VER > 11
Howard Hinnantba898e42013-09-21 01:49:28 +000065 m.lock();
66 std::vector<std::thread> v;
67 for (int i = 0; i < 5; ++i)
68 v.push_back(std::thread(f));
69 std::this_thread::sleep_for(ms(250));
70 m.unlock();
71 for (auto& t : v)
72 t.join();
Dan Albert1d4a1ed2016-05-25 22:36:09 -070073#endif // _LIBCPP_STD_VER > 11
Howard Hinnantba898e42013-09-21 01:49:28 +000074}