]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - test/std/thread/thread.mutex/thread.lock/thread.lock.shared/thread.lock.shared.cons/mutex_time_point.pass.cpp
Vendor import of libc++ trunk r290819:
[FreeBSD/FreeBSD.git] / test / std / thread / thread.mutex / thread.lock / thread.lock.shared / thread.lock.shared.cons / mutex_time_point.pass.cpp
1 //===----------------------------------------------------------------------===//
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 //===----------------------------------------------------------------------===//
9 //
10 // UNSUPPORTED: libcpp-has-no-threads
11 // UNSUPPORTED: c++98, c++03, c++11
12
13 // FLAKY_TEST.
14
15 // <shared_mutex>
16
17 // class shared_timed_mutex;
18
19 // template <class Clock, class Duration>
20 //   shared_lock(mutex_type& m, const chrono::time_point<Clock, Duration>& abs_time);
21
22 #include <shared_mutex>
23 #include <thread>
24 #include <vector>
25 #include <cstdlib>
26 #include <cassert>
27
28 #include "test_macros.h"
29
30 std::shared_timed_mutex m;
31
32 typedef std::chrono::steady_clock Clock;
33 typedef Clock::time_point time_point;
34 typedef Clock::duration duration;
35 typedef std::chrono::milliseconds ms;
36 typedef std::chrono::nanoseconds ns;
37
38 ms WaitTime = ms(250);
39
40 // Thread sanitizer causes more overhead and will sometimes cause this test
41 // to fail. To prevent this we give Thread sanitizer more time to complete the
42 // test.
43 #if !defined(TEST_HAS_SANITIZERS)
44 ms Tolerance = ms(50);
45 #else
46 ms Tolerance = ms(50 * 5);
47 #endif
48
49 void f1()
50 {
51     time_point t0 = Clock::now();
52     std::shared_lock<std::shared_timed_mutex> lk(m, Clock::now() + WaitTime + Tolerance);
53     assert(lk.owns_lock() == true);
54     time_point t1 = Clock::now();
55     ns d = t1 - t0 - WaitTime;
56     assert(d < Tolerance);  // within 50ms
57 }
58
59 void f2()
60 {
61     time_point t0 = Clock::now();
62     std::shared_lock<std::shared_timed_mutex> lk(m, Clock::now() + WaitTime);
63     assert(lk.owns_lock() == false);
64     time_point t1 = Clock::now();
65     ns d = t1 - t0 - WaitTime;
66     assert(d < Tolerance);  // within 50ms
67 }
68
69 int main()
70 {
71     {
72         m.lock();
73         std::vector<std::thread> v;
74         for (int i = 0; i < 5; ++i)
75             v.push_back(std::thread(f1));
76         std::this_thread::sleep_for(WaitTime);
77         m.unlock();
78         for (auto& t : v)
79             t.join();
80     }
81     {
82         m.lock();
83         std::vector<std::thread> v;
84         for (int i = 0; i < 5; ++i)
85             v.push_back(std::thread(f2));
86         std::this_thread::sleep_for(WaitTime + Tolerance);
87         m.unlock();
88         for (auto& t : v)
89             t.join();
90     }
91 }