Pigweed
 
Loading...
Searching...
No Matches
virtual_basic_lockable.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 "pw_polyfill/language_feature_macros.h"
17#include "pw_sync/lock_annotations.h"
18
19namespace pw::sync {
20
29class PW_LOCKABLE("pw::sync::VirtualBasicLockable") VirtualBasicLockable {
30 public:
31 void lock() PW_EXCLUSIVE_LOCK_FUNCTION() {
32 DoLockOperation(Operation::kLock);
33 }
34
35 void unlock() PW_UNLOCK_FUNCTION() { DoLockOperation(Operation::kUnlock); }
36
37 protected:
38 ~VirtualBasicLockable() = default;
39
40 enum class Operation {
41 kLock,
42 kUnlock,
43 };
44
45 private:
48 virtual void DoLockOperation(Operation operation) = 0;
49};
50
53class PW_LOCKABLE("pw::sync::NoOpLock") NoOpLock final
54 : public VirtualBasicLockable {
55 public:
56 constexpr NoOpLock() {}
57 NoOpLock(const NoOpLock&) = delete;
58 NoOpLock(NoOpLock&&) = delete;
59 NoOpLock& operator=(const NoOpLock&) = delete;
60 NoOpLock& operator=(NoOpLock&&) = delete;
61
64 static NoOpLock& Instance() {
65 PW_CONSTINIT static NoOpLock lock;
66 return lock;
67 }
68
69 private:
70 void DoLockOperation(Operation) override {}
71};
72
76template <typename LockType>
78 public:
79 virtual ~GenericBasicLockable() = default;
80
81 protected:
82 LockType& impl() { return impl_; }
83
84 private:
85 void DoLockOperation(Operation operation) override
86 PW_NO_LOCK_SAFETY_ANALYSIS {
87 switch (operation) {
88 case Operation::kLock:
89 return impl_.lock();
90
91 case Operation::kUnlock:
92 default:
93 return impl_.unlock();
94 }
95 }
96
97 LockType impl_;
98};
99
106template <typename LockType>
107class PW_LOCKABLE("pw::sync::GenericLockable") GenericLockable
108 : public GenericBasicLockable<LockType> {
109 public:
110 [[nodiscard]] bool try_lock() PW_EXCLUSIVE_TRYLOCK_FUNCTION(true) {
111 return GenericBasicLockable<LockType>::impl().try_lock();
112 }
113};
114
115} // namespace pw::sync
Definition: virtual_basic_lockable.h:77
void DoLockOperation(Operation operation) override
Definition: virtual_basic_lockable.h:85
Definition: virtual_basic_lockable.h:108
Definition: virtual_basic_lockable.h:54
void DoLockOperation(Operation) override
Definition: virtual_basic_lockable.h:70
static NoOpLock & Instance()
Definition: virtual_basic_lockable.h:64
Definition: virtual_basic_lockable.h:29
virtual void DoLockOperation(Operation operation)=0