C/C++ API Reference
Loading...
Searching...
No Matches
scoped_locker.h
1// Copyright 2025 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 <mutex>
17
18#include "pw_sync/lock_annotations.h"
19#include "pw_sync/lock_traits.h"
20
21namespace pw {
22
24
42template <typename BasicLockable>
44 public:
45 static_assert(pw::sync::is_basic_lockable_v<BasicLockable>,
46 "lock type must satisfy BasicLockable");
47
48 explicit ScopedLocker(BasicLockable& lock) noexcept
50 : lock_(lock) {
51 lock_.lock();
52 locked_ = true;
53 }
54
55 ScopedLocker(BasicLockable& lock, std::defer_lock_t) noexcept
57 : lock_(lock), locked_(false) {}
58
60 if (locked_) {
61 lock_.unlock();
62 }
63 }
64
65 ScopedLocker(const ScopedLocker&) = delete;
66 ScopedLocker(ScopedLocker&&) = delete;
67 ScopedLocker& operator=(const ScopedLocker&) = delete;
68 ScopedLocker& operator=(ScopedLocker&&) = delete;
69
70 void lock() PW_EXCLUSIVE_LOCK_FUNCTION() {
71 lock_.lock();
72 locked_ = true;
73 }
74
75 void unlock() PW_UNLOCK_FUNCTION() {
76 locked_ = false;
77 lock_.unlock();
78 }
79
80 private:
81 BasicLockable& lock_;
82 bool locked_ PW_GUARDED_BY(lock_);
83};
84
85// Deduction guide to allow ``ScopedLocker(lock)`` rather than
86// ``ScopedLocker<T>(lock)``.
87template <typename T>
89
90// Deduction guide to allow ``ScopedLocker(lock, std::defer_lock)`` rather than
91// ``ScopedLocker<T>(lock, std::defer_lock)``.
92template <typename T>
93ScopedLocker(T lock, std::defer_lock_t) -> ScopedLocker<T>;
94
96
97} // namespace pw
Definition: scoped_locker.h:43
#define PW_GUARDED_BY(x)
Definition: lock_annotations.h:60
#define PW_EXCLUSIVE_LOCK_FUNCTION(...)
Definition: lock_annotations.h:230
#define PW_SCOPED_LOCKABLE
Definition: lock_annotations.h:221
#define PW_UNLOCK_FUNCTION(...)
Definition: lock_annotations.h:247
#define PW_LOCKS_EXCLUDED(...)
Definition: lock_annotations.h:176
The Pigweed namespace.
Definition: alignment.h:27