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/light.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 PW_ASSERT(!interrupt::InInterruptContext()); 29 const int lock_count = OS_Use(&native_type_); 30 PW_ASSERT(lock_count == 1); // Recursive locking is not permitted. 31 } 32 try_lock()33inline bool Mutex::try_lock() { 34 PW_ASSERT(!interrupt::InInterruptContext()); 35 return OS_Request(&native_type_) != 0; 36 } 37 unlock()38inline void Mutex::unlock() { 39 PW_ASSERT(!interrupt::InInterruptContext()); 40 OS_Unuse(&native_type_); 41 } 42 native_handle()43inline Mutex::native_handle_type Mutex::native_handle() { return native_type_; } 44 45 } // namespace pw::sync 46