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