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 <zephyr/kernel.h> 17 18 #include "pw_assert/assert.h" 19 #include "pw_interrupt/context.h" 20 #include "pw_sync/mutex.h" 21 22 namespace pw::sync { 23 Mutex()24inline Mutex::Mutex() : native_type_() { k_mutex_init(&native_type_); } 25 26 inline Mutex::~Mutex() = default; 27 lock()28inline void Mutex::lock() { 29 PW_DASSERT(!interrupt::InInterruptContext()); 30 k_mutex_lock(&native_type_, K_FOREVER); 31 PW_DASSERT(native_type_.lock_count == 1); 32 } 33 try_lock()34inline bool Mutex::try_lock() { 35 PW_DASSERT(!interrupt::InInterruptContext()); 36 37 bool result = k_mutex_lock(&native_type_, K_NO_WAIT) == 0; 38 PW_DASSERT(native_type_.lock_count <= 1); 39 40 return result; 41 } 42 unlock()43inline void Mutex::unlock() { 44 PW_DASSERT(!interrupt::InInterruptContext()); 45 PW_ASSERT(k_mutex_unlock(&native_type_) == 0); 46 } 47 native_handle()48inline Mutex::native_handle_type Mutex::native_handle() { return native_type_; } 49 50 } // namespace pw::sync 51