Debian Codegraph @

libcxx/test/std/thread/thread.mutex/thread.mutex.requirements/thread.shared_mutex.requirements/thread.shared_mutex.class/lock_shared.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, c++14
11
12 // ALLOW_RETRIES: 2
13
14 // <shared_mutex>
15
16 // class shared_mutex;
17
18 // void lock_shared();
19
20 #include <cassert>
21 #include <chrono>
22 #include <cstdlib>
23 #include <shared_mutex>
24 #include <thread>
25 #include <vector>
26
27 #include "make_test_thread.h"
28 #include "test_macros.h"
29
30 std::shared_mutex m;
31
32 typedef std::chrono::system_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_IS_EXECUTED_IN_A_SLOW_ENVIRONMENT)
44 ms Tolerance = ms(50);
45 #else
46 ms Tolerance = ms(50 * 5);
47 #endif
48
49 void f()
50 {
51 time_point t0 = Clock::now();
52 m.lock_shared();
53 time_point t1 = Clock::now();
54 m.unlock_shared();
55 ns d = t1 - t0 - WaitTime;
56 assert(d < Tolerance); // within tolerance
57 }
58
59 void g()
60 {
61 time_point t0 = Clock::now();
62 m.lock_shared();
63 time_point t1 = Clock::now();
64 m.unlock_shared();
65 ns d = t1 - t0;
66 assert(d < Tolerance); // within tolerance
67 }
68
69
70 int main(int, char**)
71 {
72 m.lock();
73 std::vector<std::thread> v;
74 for (int i = 0; i < 5; ++i)
75 v.push_back(support::make_test_thread(f));
76 std::this_thread::sleep_for(WaitTime);
77 m.unlock();
78 for (auto& t : v)
79 t.join();
80 m.lock_shared();
81 for (auto& t : v)
82 t = support::make_test_thread(g);
83 std::thread q = support::make_test_thread(f);
84 std::this_thread::sleep_for(WaitTime);
85 m.unlock_shared();
86 for (auto& t : v)
87 t.join();
88 q.join();
89
90 return 0;
91 }