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 // template <class Rep, class Period> 15 // bool try_lock_for(const chrono::duration<Rep, Period>& rel_time); 16 17 #include <mutex> 18 #include <cassert> 19 20 bool try_lock_for_called = false; 21 22 typedef std::chrono::milliseconds ms; 23 24 struct mutex 25 { 26 template <class Rep, class Period> 27 bool try_lock_for(const std::chrono::duration<Rep, Period>& rel_time) 28 { 29 assert(rel_time == ms(5)); 30 try_lock_for_called = !try_lock_for_called; 31 return try_lock_for_called; 32 } 33 void unlock() {} 34 }; 35 36 mutex m; 37 38 int main() 39 { 40 std::unique_lock<mutex> lk(m, std::defer_lock); 41 assert(lk.try_lock_for(ms(5)) == true); 42 assert(try_lock_for_called == true); 43 assert(lk.owns_lock() == true); 44 try 45 { 46 lk.try_lock_for(ms(5)); 47 assert(false); 48 } 49 catch (std::system_error& e) 50 { 51 assert(e.code().value() == EDEADLK); 52 } 53 lk.unlock(); 54 assert(lk.try_lock_for(ms(5)) == false); 55 assert(try_lock_for_called == false); 56 assert(lk.owns_lock() == false); 57 lk.release(); 58 try 59 { 60 lk.try_lock_for(ms(5)); 61 assert(false); 62 } 63 catch (std::system_error& e) 64 { 65 assert(e.code().value() == EPERM); 66 } 67 } 68