1 // Copyright 2020 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 "pw_assert/light.h" 17 #include "pw_interrupt/context.h" 18 #include "pw_sync/mutex.h" 19 #include "tx_api.h" 20 21 namespace pw::sync { 22 namespace backend { 23 24 inline constexpr char kMutexName[] = "pw::Mutex"; 25 26 } // namespace backend 27 Mutex()28inline Mutex::Mutex() : native_type_() { 29 PW_ASSERT(tx_mutex_create(&native_type_, 30 const_cast<char*>(backend::kMutexName), 31 TX_INHERIT) == TX_SUCCESS); 32 } 33 ~Mutex()34inline Mutex::~Mutex() { 35 PW_ASSERT(tx_mutex_delete(&native_type_) == TX_SUCCESS); 36 } 37 lock()38inline void Mutex::lock() { 39 // Enforce the pw::sync::Mutex IRQ contract. 40 PW_ASSERT(!interrupt::InInterruptContext()); 41 PW_ASSERT(tx_mutex_get(&native_type_, TX_WAIT_FOREVER) == TX_SUCCESS); 42 } 43 try_lock()44inline bool Mutex::try_lock() { 45 // Enforce the pw::sync::Mutex IRQ contract. 46 PW_ASSERT(!interrupt::InInterruptContext()); 47 const UINT result = tx_mutex_get(&native_type_, TX_NO_WAIT); 48 if (result == TX_NOT_AVAILABLE) { 49 return false; 50 } 51 PW_ASSERT(result == TX_SUCCESS); 52 return true; 53 } 54 unlock()55inline void Mutex::unlock() { 56 // Enforce the pw::sync::Mutex IRQ contract. 57 PW_ASSERT(!interrupt::InInterruptContext()); 58 PW_ASSERT(tx_mutex_put(&native_type_) == TX_SUCCESS); 59 } 60 native_handle()61inline Mutex::native_handle_type Mutex::native_handle() { return native_type_; } 62 63 } // namespace pw::sync 64