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: libcpp-has-no-threads 10 // UNSUPPORTED: c++98, c++03, c++11 11 12 // FLAKY_TEST. 13 14 // <shared_mutex> 15 16 // class timed_mutex; 17 18 // template <class Rep, class Period> 19 // shared_lock(mutex_type& m, const chrono::duration<Rep, Period>& rel_time); 20 21 #include <shared_mutex> 22 #include <thread> 23 #include <vector> 24 #include <cstdlib> 25 #include <cassert> 26 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 ms WaitTime = ms(250); 38 39 // Thread sanitizer causes more overhead and will sometimes cause this test 40 // to fail. To prevent this we give Thread sanitizer more time to complete the 41 // test. 42 #if !defined(TEST_HAS_SANITIZERS) 43 ms Tolerance = ms(50); 44 #else 45 ms Tolerance = ms(50 * 5); 46 #endif 47 48 49 void f1() 50 { 51 time_point t0 = Clock::now(); 52 std::shared_lock<std::shared_timed_mutex> lk(m, 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, 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(int, char**) 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 92 return 0; 93 } 94