1 // Copyright 2022 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 <limits> 17 18 #include "pw_assert/assert.h" 19 #include "pw_sync/recursive_mutex.h" 20 21 namespace pw::sync { 22 RecursiveMutex()23inline RecursiveMutex::RecursiveMutex() : native_type_(0) {} 24 25 inline RecursiveMutex::~RecursiveMutex() = default; 26 lock()27inline void RecursiveMutex::lock() { 28 try_lock(); // Locking always succeeds 29 } 30 try_lock()31inline bool RecursiveMutex::try_lock() { 32 int lock_count = native_type_.fetch_add(1, std::memory_order_acquire); 33 PW_DASSERT(lock_count != std::numeric_limits<int>::max()); // Detect overflow 34 return true; // No threads, so you can always acquire a recursive mutex. 35 } 36 unlock()37inline void RecursiveMutex::unlock() { 38 int lock_count = native_type_.fetch_sub(1, std::memory_order_release); 39 PW_ASSERT(lock_count > 0); // Unlocked mutex that wasn't held 40 } 41 native_handle()42inline RecursiveMutex::native_handle_type RecursiveMutex::native_handle() { 43 return native_type_; 44 } 45 46 } // namespace pw::sync 47