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++03, c++98, c++11 12 13 // <shared_mutex> 14 15 // class shared_timed_mutex; 16 17 // template <class Clock, class Duration> 18 // bool try_lock_shared_until(const chrono::time_point<Clock, Duration>& abs_time); 19 20 #include <shared_mutex> 21 #include <thread> 22 #include <vector> 23 #include <cstdlib> 24 #include <cassert> 25 26 std::shared_timed_mutex m; 27 28 typedef std::chrono::steady_clock Clock; 29 typedef Clock::time_point time_point; 30 typedef Clock::duration duration; 31 typedef std::chrono::milliseconds ms; 32 typedef std::chrono::nanoseconds ns; 33 f1()34void f1() 35 { 36 time_point t0 = Clock::now(); 37 assert(m.try_lock_shared_until(Clock::now() + ms(300)) == true); 38 time_point t1 = Clock::now(); 39 m.unlock_shared(); 40 ns d = t1 - t0 - ms(250); 41 assert(d < ms(50)); // within 50ms 42 } 43 f2()44void f2() 45 { 46 time_point t0 = Clock::now(); 47 assert(m.try_lock_shared_until(Clock::now() + ms(250)) == false); 48 time_point t1 = Clock::now(); 49 ns d = t1 - t0 - ms(250); 50 assert(d < ms(50)); // within 50ms 51 } 52 main()53int main() 54 { 55 { 56 m.lock(); 57 std::vector<std::thread> v; 58 for (int i = 0; i < 5; ++i) 59 v.push_back(std::thread(f1)); 60 std::this_thread::sleep_for(ms(250)); 61 m.unlock(); 62 for (auto& t : v) 63 t.join(); 64 } 65 { 66 m.lock(); 67 std::vector<std::thread> v; 68 for (int i = 0; i < 5; ++i) 69 v.push_back(std::thread(f2)); 70 std::this_thread::sleep_for(ms(300)); 71 m.unlock(); 72 for (auto& t : v) 73 t.join(); 74 } 75 } 76