C/C++ API Reference
Loading...
Searching...
No Matches
timed_borrow.h
1// Copyright 2021 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#pragma once
15
16#include <optional>
17#include <type_traits>
18
19#include "pw_chrono/system_clock.h"
20#include "pw_sync/borrow.h"
21#include "pw_sync/lock_annotations.h"
22#include "pw_sync/lock_traits.h"
23#include "pw_sync/virtual_basic_lockable.h"
24
25namespace pw::sync {
26
28
32template <typename GuardedType,
33 typename LockType = pw::sync::VirtualBasicLockable>
34class TimedBorrowable : public Borrowable<GuardedType, LockType> {
35 private:
37
38 static_assert(is_lockable_for_v<LockType, chrono::SystemClock::duration>);
39 static_assert(is_lockable_until_v<LockType, chrono::SystemClock::time_point>);
40
41 public:
42 constexpr TimedBorrowable(GuardedType& object, LockType& lock) noexcept
43 : Base(object, lock) {}
44
45 template <typename U>
46 constexpr TimedBorrowable(const Borrowable<U, LockType>& other)
47 : Base(other) {}
48
53 std::optional<BorrowedPointer<GuardedType, LockType>> try_acquire_for(
55 if (!Base::lock_->try_lock_for(timeout)) {
56 return std::nullopt;
57 }
58 return Base::Borrow();
59 }
60
64 std::optional<BorrowedPointer<GuardedType, LockType>> try_acquire_until(
65 chrono::SystemClock::time_point deadline) const
67 if (!Base::lock_->try_lock_until(deadline)) {
68 return std::nullopt;
69 }
70 return Base::Borrow();
71 }
72};
73
75
76} // namespace pw::sync
Definition: borrow.h:164
Definition: timed_borrow.h:34
std::optional< BorrowedPointer< GuardedType, LockType > > try_acquire_for(chrono::SystemClock::duration timeout) const
Definition: timed_borrow.h:53
std::optional< BorrowedPointer< GuardedType, LockType > > try_acquire_until(chrono::SystemClock::time_point deadline) const
Definition: timed_borrow.h:64
Definition: virtual_basic_lockable.h:31
std::chrono::duration< rep, period > duration
Alias for durations representable with this clock.
Definition: system_clock.h:90
#define PW_NO_LOCK_SAFETY_ANALYSIS
Definition: lock_annotations.h:292
Definition: binary_semaphore.h:26