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++98, c++03, c++11 12 13 // FLAKY_TEST. 14 15 // <shared_mutex> 16 17 // class timed_mutex; 18 19 // template <class Rep, class Period> 20 // shared_lock(mutex_type& m, const chrono::duration<Rep, Period>& rel_time); 21 22 #include <shared_mutex> 23 #include <thread> 24 #include <vector> 25 #include <cstdlib> 26 #include <cassert> 27 28 #include "test_macros.h" 29 30 std::shared_timed_mutex m; 31 32 typedef std::chrono::steady_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_HAS_SANITIZERS) 44 ms Tolerance = ms(50); 45 #else 46 ms Tolerance = ms(50 * 5); 47 #endif 48 49 f1()50void f1() 51 { 52 time_point t0 = Clock::now(); 53 std::shared_lock<std::shared_timed_mutex> lk(m, WaitTime + Tolerance); 54 assert(lk.owns_lock() == true); 55 time_point t1 = Clock::now(); 56 ns d = t1 - t0 - WaitTime; 57 assert(d < Tolerance); // within 50ms 58 } 59 f2()60void f2() 61 { 62 time_point t0 = Clock::now(); 63 std::shared_lock<std::shared_timed_mutex> lk(m, WaitTime); 64 assert(lk.owns_lock() == false); 65 time_point t1 = Clock::now(); 66 ns d = t1 - t0 - WaitTime; 67 assert(d < Tolerance); // within 50ms 68 } 69 main()70int main() 71 { 72 { 73 m.lock(); 74 std::vector<std::thread> v; 75 for (int i = 0; i < 5; ++i) 76 v.push_back(std::thread(f1)); 77 std::this_thread::sleep_for(WaitTime); 78 m.unlock(); 79 for (auto& t : v) 80 t.join(); 81 } 82 { 83 m.lock(); 84 std::vector<std::thread> v; 85 for (int i = 0; i < 5; ++i) 86 v.push_back(std::thread(f2)); 87 std::this_thread::sleep_for(WaitTime + Tolerance); 88 m.unlock(); 89 for (auto& t : v) 90 t.join(); 91 } 92 } 93