Debian Codegraph @

libcxx/test/std/thread/thread.mutex/thread.mutex.requirements/thread.sharedtimedmutex.requirements/thread.sharedtimedmutex.class/try_lock_for.pass.cpp

raw
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // UNSUPPORTED: no-threads
10 // UNSUPPORTED: c++03, c++11
11 // ALLOW_RETRIES: 2
12
13 // <shared_mutex>
14
15 // class shared_timed_mutex;
16
17 // template <class Rep, class Period>
18 // bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
19
20 #include <shared_mutex>
21 #include <thread>
22 #include <cstdlib>
23 #include <cassert>
24 #include <chrono>
25
26 #include "make_test_thread.h"
27 #include "test_macros.h"
28
29 std::shared_timed_mutex m;
30
31 typedef std::chrono::steady_clock Clock;
32 typedef Clock::time_point time_point;
33 typedef Clock::duration duration;
34 typedef std::chrono::milliseconds ms;
35 typedef std::chrono::nanoseconds ns;
36
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_IS_EXECUTED_IN_A_SLOW_ENVIRONMENT)
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 assert(m.try_lock_for(WaitTime + Tolerance) == true);
53 time_point t1 = Clock::now();
54 m.unlock();
55 ns d = t1 - t0 - WaitTime;
56 assert(d < Tolerance); // within tolerance
57 }
58
59 void f2()
60 {
61 time_point t0 = Clock::now();
62 assert(m.try_lock_for(WaitTime) == false);
63 time_point t1 = Clock::now();
64 ns d = t1 - t0 - WaitTime;
65 assert(d < Tolerance); // within tolerance
66 }
67
68 int main(int, char**)
69 {
70 {
71 m.lock();
72 std::thread t = support::make_test_thread(f1);
73 std::this_thread::sleep_for(WaitTime);
74 m.unlock();
75 t.join();
76 }
77 {
78 m.lock();
79 std::thread t = support::make_test_thread(f2);
80 std::this_thread::sleep_for(WaitTime + Tolerance);
81 m.unlock();
82 t.join();
83 }
84
85 return 0;
86 }