C/C++ API Reference
Loading...
Searching...
No Matches
checker.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 <optional>
17
18#include "pw_sync/lock_annotations.h"
19#include "pw_thread/config.h"
20#include "pw_thread/thread.h"
21
22namespace pw {
23
25
53class PW_LOCKABLE("pw::ThreadChecker") ThreadChecker {
54 public:
55 explicit ThreadChecker(Thread::id id) : self_(id) {}
56
57 // Implementation of the BaseLockable requirement
58 void lock() PW_EXCLUSIVE_LOCK_FUNCTION() {
59#if PW_THREAD_CHECKER_RUNTIME_ASSERT_ENABLED
60 // Hitting this assert means that access to this checker from multiple
61 // threads was detected.
62 PW_ASSERT(pw::this_thread::get_id() == self_);
63#endif // PW_THREAD_CHECKER_RUNTIME_ASSERT_ENABLED
64 }
65 void unlock() PW_UNLOCK_FUNCTION() {}
66
67 private:
68 Thread::id self_;
69};
70
77class PW_LOCKABLE("pw::LazyInitThreadChecker") LazyInitThreadChecker {
78 public:
79 // Implementation of the BaseLockable requirement
80 void lock() PW_EXCLUSIVE_LOCK_FUNCTION() {
81#if PW_THREAD_CHECKER_RUNTIME_ASSERT_ENABLED
82 if (!checker_.has_value()) {
83 checker_.emplace(pw::this_thread::get_id());
84 }
85 checker_->lock();
86#endif // PW_THREAD_CHECKER_RUNTIME_ASSERT_ENABLED
87 }
88 void unlock() PW_UNLOCK_FUNCTION() {}
89
90 private:
91#if PW_THREAD_CHECKER_RUNTIME_ASSERT_ENABLED
92 std::optional<ThreadChecker> checker_;
93#endif // PW_THREAD_CHECKER_RUNTIME_ASSERT_ENABLED
94};
95
96} // namespace pw
Definition: checker.h:77
Definition: checker.h:53
#define PW_LOCKABLE(name)
Definition: lock_annotations.h:208
#define PW_EXCLUSIVE_LOCK_FUNCTION(...)
Definition: lock_annotations.h:230
#define PW_UNLOCK_FUNCTION(...)
Definition: lock_annotations.h:247
::pw::thread::backend::NativeId id
Definition: thread.h:90
The Pigweed namespace.
Definition: alignment.h:27