xref: /aosp_15_r20/external/pigweed/pw_sync_zephyr/public/pw_sync_zephyr/mutex_inline.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
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()24 inline Mutex::Mutex() : native_type_() { k_mutex_init(&native_type_); }
25 
26 inline Mutex::~Mutex() = default;
27 
lock()28 inline 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()34 inline 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()43 inline void Mutex::unlock() {
44   PW_DASSERT(!interrupt::InInterruptContext());
45   PW_ASSERT(k_mutex_unlock(&native_type_) == 0);
46 }
47 
native_handle()48 inline Mutex::native_handle_type Mutex::native_handle() { return native_type_; }
49 
50 }  // namespace pw::sync
51