1 // Copyright 2021 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 "RTOS.h" 17 #include "pw_assert/assert.h" 18 #include "pw_interrupt/context.h" 19 #include "pw_sync/mutex.h" 20 21 namespace pw::sync { 22 Mutex()23inline Mutex::Mutex() : native_type_() { OS_CreateRSema(&native_type_); } 24 ~Mutex()25inline Mutex::~Mutex() { OS_DeleteRSema(&native_type_); } 26 lock()27inline void Mutex::lock() { 28 // Enforce the pw::sync::Mutex IRQ contract. 29 PW_DASSERT(!interrupt::InInterruptContext()); 30 const int lock_count = OS_Use(&native_type_); 31 PW_DASSERT(lock_count == 1); // Recursive locking is not permitted. 32 } 33 try_lock()34inline bool Mutex::try_lock() { 35 // Enforce the pw::sync::Mutex IRQ contract. 36 PW_DASSERT(!interrupt::InInterruptContext()); 37 if (OS_Request(&native_type_) == 0) { 38 return false; 39 } 40 41 // Recursive locking is not permitted. 42 PW_DASSERT(OS_GetSemaValue(&native_type_) == 1); 43 return true; 44 } 45 unlock()46inline void Mutex::unlock() { 47 // Enforce the pw::sync::Mutex IRQ contract. 48 PW_DASSERT(!interrupt::InInterruptContext()); 49 OS_Unuse(&native_type_); 50 } 51 native_handle()52inline Mutex::native_handle_type Mutex::native_handle() { return native_type_; } 53 54 } // namespace pw::sync 55