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

source code of libcxx/test/std/thread/thread.mutex/thread.lock/thread.lock.unique/thread.lock.unique.locking/try_lock_for.pass.cpp