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 // <mutex> 10 11 // template <class Mutex> class unique_lock; 12 13 // bool try_lock(); 14 15 #include <cassert> 16 #include <mutex> 17 #include <system_error> 18 19 #include "test_macros.h" 20 #include "checking_mutex.h" 21 22 int main(int, char**) { 23 checking_mutex mux; 24 25 std::unique_lock<checking_mutex> lock(mux, std::defer_lock_t()); 26 assert(lock.try_lock()); 27 assert(mux.current_state == checking_mutex::locked_via_try_lock); 28 assert(lock.owns_lock()); 29 30 #ifndef TEST_HAS_NO_EXCEPTIONS 31 try { 32 mux.last_try = checking_mutex::none; 33 TEST_IGNORE_NODISCARD lock.try_lock(); 34 assert(false); 35 } catch (std::system_error& e) { 36 assert(mux.last_try == checking_mutex::none); 37 assert(e.code() == std::errc::resource_deadlock_would_occur); 38 } 39 #endif 40 41 lock.unlock(); 42 mux.reject = true; 43 44 assert(!lock.try_lock()); 45 assert(mux.last_try == checking_mutex::locked_via_try_lock); 46 47 assert(!lock.owns_lock()); 48 lock.release(); 49 50 #ifndef TEST_HAS_NO_EXCEPTIONS 51 try { 52 mux.last_try = checking_mutex::none; 53 (void)lock.try_lock(); 54 assert(false); 55 } catch (std::system_error& e) { 56 assert(mux.last_try == checking_mutex::none); 57 assert(e.code() == std::errc::operation_not_permitted); 58 } 59 #endif 60 61 return 0; 62 } 63