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 // bool try_lock(); 15 16 #include <mutex> 17 #include <cassert> 18 19 bool try_lock_called = false; 20 21 struct mutex 22 { try_lockmutex23 bool try_lock() 24 { 25 try_lock_called = !try_lock_called; 26 return try_lock_called; 27 } unlockmutex28 void unlock() {} 29 }; 30 31 mutex m; 32 main()33int main() 34 { 35 std::unique_lock<mutex> lk(m, std::defer_lock); 36 assert(lk.try_lock() == true); 37 assert(try_lock_called == true); 38 assert(lk.owns_lock() == true); 39 try 40 { 41 lk.try_lock(); 42 assert(false); 43 } 44 catch (std::system_error& e) 45 { 46 assert(e.code().value() == EDEADLK); 47 } 48 lk.unlock(); 49 assert(lk.try_lock() == false); 50 assert(try_lock_called == false); 51 assert(lk.owns_lock() == false); 52 lk.release(); 53 try 54 { 55 lk.try_lock(); 56 assert(false); 57 } 58 catch (std::system_error& e) 59 { 60 assert(e.code().value() == EPERM); 61 } 62 } 63