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 12 // <mutex> 13 14 // template <class Mutex> class unique_lock; 15 16 // bool try_lock(); 17 18 #include <mutex> 19 #include <cassert> 20 21 #include "test_macros.h" 22 23 bool try_lock_called = false; 24 25 struct mutex 26 { try_lockmutex27 bool try_lock() 28 { 29 try_lock_called = !try_lock_called; 30 return try_lock_called; 31 } unlockmutex32 void unlock() {} 33 }; 34 35 mutex m; 36 main()37int main() 38 { 39 std::unique_lock<mutex> lk(m, std::defer_lock); 40 assert(lk.try_lock() == true); 41 assert(try_lock_called == true); 42 assert(lk.owns_lock() == true); 43 #ifndef TEST_HAS_NO_EXCEPTIONS 44 try 45 { 46 TEST_IGNORE_NODISCARD lk.try_lock(); 47 assert(false); 48 } 49 catch (std::system_error& e) 50 { 51 assert(e.code().value() == EDEADLK); 52 } 53 #endif 54 lk.unlock(); 55 assert(lk.try_lock() == false); 56 assert(try_lock_called == false); 57 assert(lk.owns_lock() == false); 58 lk.release(); 59 #ifndef TEST_HAS_NO_EXCEPTIONS 60 try 61 { 62 TEST_IGNORE_NODISCARD lk.try_lock(); 63 assert(false); 64 } 65 catch (std::system_error& e) 66 { 67 assert(e.code().value() == EPERM); 68 } 69 #endif 70 } 71