1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // UNSUPPORTED: libcpp-has-no-threads 10 11 // <mutex> 12 13 // template <class Mutex> class unique_lock; 14 15 // bool try_lock(); 16 17 #include <mutex> 18 #include <cassert> 19 20 #include "test_macros.h" 21 22 bool try_lock_called = false; 23 24 struct mutex 25 { 26 bool try_lock() 27 { 28 try_lock_called = !try_lock_called; 29 return try_lock_called; 30 } 31 void unlock() {} 32 }; 33 34 mutex m; 35 36 int main(int, char**) 37 { 38 std::unique_lock<mutex> lk(m, std::defer_lock); 39 assert(lk.try_lock() == true); 40 assert(try_lock_called == true); 41 assert(lk.owns_lock() == true); 42 #ifndef TEST_HAS_NO_EXCEPTIONS 43 try 44 { 45 TEST_IGNORE_NODISCARD lk.try_lock(); 46 assert(false); 47 } 48 catch (std::system_error& e) 49 { 50 assert(e.code().value() == EDEADLK); 51 } 52 #endif 53 lk.unlock(); 54 assert(lk.try_lock() == false); 55 assert(try_lock_called == false); 56 assert(lk.owns_lock() == false); 57 lk.release(); 58 #ifndef TEST_HAS_NO_EXCEPTIONS 59 try 60 { 61 TEST_IGNORE_NODISCARD lk.try_lock(); 62 assert(false); 63 } 64 catch (std::system_error& e) 65 { 66 assert(e.code().value() == EPERM); 67 } 68 #endif 69 70 return 0; 71 } 72