Debian Codegraph @

libcxx/test/std/thread/thread.mutex/thread.mutex.requirements/thread.sharedtimedmutex.requirements/thread.sharedtimedmutex.class/try_lock_shared_until.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
12 // ALLOW_RETRIES: 2
13
14 // <shared_mutex>
15
16 // class shared_timed_mutex;
17
18 // template <class Clock, class Duration>
19 // bool try_lock_shared_until(const chrono::time_point<Clock, Duration>& abs_time);
20
21 #include <thread>
22
23 #include <atomic>
24 #include <cassert>
25 #include <chrono>
26 #include <cstdlib>
27 #include <shared_mutex>
28 #include <vector>
29
30 #include "make_test_thread.h"
31 #include "test_macros.h"
32
33 std::shared_timed_mutex m;
34
35 typedef std::chrono::steady_clock Clock;
36 typedef Clock::time_point time_point;
37 typedef Clock::duration duration;
38 typedef std::chrono::milliseconds ms;
39 typedef std::chrono::nanoseconds ns;
40
41 ms SuccessWaitTime = ms(5000); // Some machines are busy or slow or both
42 ms FailureWaitTime = ms(50);
43
44 // On busy or slow machines, there can be a significant delay between thread
45 // creation and thread start, so we use an atomic variable to signal that the
46 // thread is actually executing.
47 static std::atomic<unsigned> countDown;
48
49 void f1()
50 {
51 --countDown;
52 time_point t0 = Clock::now();
53 assert(m.try_lock_shared_until(Clock::now() + SuccessWaitTime) == true);
54 time_point t1 = Clock::now();
55 m.unlock_shared();
56 assert(t1 - t0 <= SuccessWaitTime);
57 }
58
59 void f2()
60 {
61 time_point t0 = Clock::now();
62 assert(m.try_lock_shared_until(Clock::now() + FailureWaitTime) == false);
63 assert(Clock::now() - t0 >= FailureWaitTime);
64 }
65
66 int main(int, char**)
67 {
68 int threads = 5;
69 {
70 countDown.store(threads);
71 m.lock();
72 std::vector<std::thread> v;
73 for (int i = 0; i < threads; ++i)
74 v.push_back(support::make_test_thread(f1));
75 while (countDown > 0)
76 std::this_thread::yield();
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 < threads; ++i)
85 v.push_back(support::make_test_thread(f2));
86 for (auto& t : v)
87 t.join();
88 m.unlock();
89 }
90
91 return 0;
92 }