blob: 501036535c32b65c6fedd586134a2f2e6e7b64dc (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
// Copyright 2021 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#pragma once
#include "pw_polyfill/language_feature_macros.h"
#include "pw_sync/lock_annotations.h"
namespace pw::sync {
/// The `VirtualBasicLockable` is a virtual lock abstraction for locks which
/// meet the C++ named BasicLockable requirements of lock() and unlock().
///
/// This virtual indirection is useful in case you need configurable lock
/// selection in a portable module where the final type is not defined upstream
/// and ergo module configuration cannot be used or in case the lock type is not
/// fixed at compile time, for example to support run time and crash time use of
/// an object without incurring the code size hit for templating the object.
class PW_LOCKABLE("pw::sync::VirtualBasicLockable") VirtualBasicLockable {
public:
void lock() PW_EXCLUSIVE_LOCK_FUNCTION() {
DoLockOperation(Operation::kLock);
}
void unlock() PW_UNLOCK_FUNCTION() { DoLockOperation(Operation::kUnlock); }
protected:
~VirtualBasicLockable() = default;
enum class Operation {
kLock,
kUnlock,
};
private:
/// Uses a single virtual method with an enum to minimize the vtable cost per
/// implementation of `VirtualBasicLockable`.
virtual void DoLockOperation(Operation operation) = 0;
};
/// The `NoOpLock` is a type of `VirtualBasicLockable` that does nothing, i.e.
/// lock operations are no-ops.
class PW_LOCKABLE("pw::sync::NoOpLock") NoOpLock final
: public VirtualBasicLockable {
public:
constexpr NoOpLock() {}
NoOpLock(const NoOpLock&) = delete;
NoOpLock(NoOpLock&&) = delete;
NoOpLock& operator=(const NoOpLock&) = delete;
NoOpLock& operator=(NoOpLock&&) = delete;
/// Gives access to a global NoOpLock instance. It is not necessary to have
/// multiple NoOpLock instances since they have no state and do nothing.
static NoOpLock& Instance() {
PW_CONSTINIT static NoOpLock lock;
return lock;
}
private:
void DoLockOperation(Operation) override {}
};
} // namespace pw::sync
|