Pigweed
 
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
30template <typename GuardedType,
31 typename LockType = pw::sync::VirtualBasicLockable>
32class TimedBorrowable : public Borrowable<GuardedType, LockType> {
33 private:
35
36 static_assert(is_lockable_for_v<LockType, chrono::SystemClock::duration>);
37 static_assert(is_lockable_until_v<LockType, chrono::SystemClock::time_point>);
38
39 public:
40 constexpr TimedBorrowable(GuardedType& object, LockType& lock) noexcept
41 : Base(object, lock) {}
42
43 template <typename U>
44 constexpr TimedBorrowable(const Borrowable<U, LockType>& other)
45 : Base(other) {}
46
50 std::optional<BorrowedPointer<GuardedType, LockType>> try_acquire_for(
51 chrono::SystemClock::duration timeout) const PW_NO_LOCK_SAFETY_ANALYSIS {
52 if (!Base::lock_->try_lock_for(timeout)) {
53 return std::nullopt;
54 }
55 return Base::Borrow();
56 }
57
61 std::optional<BorrowedPointer<GuardedType, LockType>> try_acquire_until(
62 chrono::SystemClock::time_point deadline) const
63 PW_NO_LOCK_SAFETY_ANALYSIS {
64 if (!Base::lock_->try_lock_until(deadline)) {
65 return std::nullopt;
66 }
67 return Base::Borrow();
68 }
69};
70
71} // namespace pw::sync
Definition: borrow.h:164
Definition: timed_borrow.h:32
std::optional< BorrowedPointer< GuardedType, LockType > > try_acquire_for(chrono::SystemClock::duration timeout) const
Definition: timed_borrow.h:50
std::optional< BorrowedPointer< GuardedType, LockType > > try_acquire_until(chrono::SystemClock::time_point deadline) const
Definition: timed_borrow.h:61
Definition: virtual_basic_lockable.h:29
std::chrono::duration< rep, period > duration
Alias for durations representable with this clock.
Definition: system_clock.h:86