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