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 // <shared_mutex> 14 15 // template <class Mutex> class shared_lock; 16 17 // shared_lock(mutex_type& m, try_to_lock_t); 18 19 #include <shared_mutex> 20 #include <thread> 21 #include <vector> 22 #include <cstdlib> 23 #include <cassert> 24 25 std::shared_timed_mutex m; 26 27 typedef std::chrono::system_clock Clock; 28 typedef Clock::time_point time_point; 29 typedef Clock::duration duration; 30 typedef std::chrono::milliseconds ms; 31 typedef std::chrono::nanoseconds ns; 32 33 void f() 34 { 35 time_point t0 = Clock::now(); 36 { 37 std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock); 38 assert(lk.owns_lock() == false); 39 } 40 { 41 std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock); 42 assert(lk.owns_lock() == false); 43 } 44 { 45 std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock); 46 assert(lk.owns_lock() == false); 47 } 48 while (true) 49 { 50 std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock); 51 if (lk.owns_lock()) 52 break; 53 } 54 time_point t1 = Clock::now(); 55 ns d = t1 - t0 - ms(250); 56 assert(d < ms(200)); // within 200ms 57 } 58 59 int main() 60 { 61 m.lock(); 62 std::vector<std::thread> v; 63 for (int i = 0; i < 5; ++i) 64 v.push_back(std::thread(f)); 65 std::this_thread::sleep_for(ms(250)); 66 m.unlock(); 67 for (auto& t : v) 68 t.join(); 69 } 70