Pigweed
C/C++ API Reference
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
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
51class PW_LOCKABLE("pw::ThreadChecker") ThreadChecker {
52 public:
53 explicit ThreadChecker(Thread::id id) : self_(id) {}
54
55 // Implementation of the BaseLockable requirement
56 void lock() PW_EXCLUSIVE_LOCK_FUNCTION() {
57#if PW_THREAD_CHECKER_RUNTIME_ASSERT_ENABLED
58 // Hitting this assert means that access to this checker from multiple
59 // threads was detected.
60 PW_ASSERT(pw::this_thread::get_id() == self_);
61#endif // PW_THREAD_CHECKER_RUNTIME_ASSERT_ENABLED
62 }
63 void unlock() PW_UNLOCK_FUNCTION() {}
64
65 private:
66 Thread::id self_;
67};
68
75class PW_LOCKABLE("pw::LazyInitThreadChecker") LazyInitThreadChecker {
76 public:
77 // Implementation of the BaseLockable requirement
78 void lock() PW_EXCLUSIVE_LOCK_FUNCTION() {
79#if PW_THREAD_CHECKER_RUNTIME_ASSERT_ENABLED
80 if (!checker_.has_value()) {
81 checker_.emplace(pw::this_thread::get_id());
82 }
83 checker_->lock();
84#endif // PW_THREAD_CHECKER_RUNTIME_ASSERT_ENABLED
85 }
86 void unlock() PW_UNLOCK_FUNCTION() {}
87
88 private:
89#if PW_THREAD_CHECKER_RUNTIME_ASSERT_ENABLED
90 std::optional<ThreadChecker> checker_;
91#endif // PW_THREAD_CHECKER_RUNTIME_ASSERT_ENABLED
92};
93
94} // namespace pw
Definition: checker.h:75
Definition: checker.h:51
::pw::thread::backend::NativeId id
Definition: thread.h:86
Provides basic helpers for reading and writing UTF-8 encoded strings.
Definition: alignment.h:27