xref: /aosp_15_r20/external/pigweed/pw_sync_zephyr/public/pw_sync_zephyr/binary_semaphore_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_chrono/system_clock.h"
20 #include "pw_interrupt/context.h"
21 #include "pw_sync/binary_semaphore.h"
22 
23 namespace pw::sync {
24 
BinarySemaphore()25 inline BinarySemaphore::BinarySemaphore() : native_type_() {
26   constexpr unsigned int kInitialCount = 0;
27   k_sem_init(&native_type_, kInitialCount, backend::kBinarySemaphoreMaxValue);
28 }
29 
30 inline BinarySemaphore::~BinarySemaphore() = default;
31 
release()32 inline void BinarySemaphore::release() {
33   PW_DASSERT(!interrupt::InInterruptContext());
34   k_sem_give(&native_type_);
35 }
36 
acquire()37 inline void BinarySemaphore::acquire() {
38   PW_DASSERT(!interrupt::InInterruptContext());
39   PW_ASSERT(k_sem_take(&native_type_, K_FOREVER) == 0);
40 }
41 
try_acquire()42 inline bool BinarySemaphore::try_acquire() noexcept {
43   return k_sem_take(&native_type_, K_NO_WAIT) == 0;
44 }
45 
try_acquire_until(chrono::SystemClock::time_point deadline)46 inline bool BinarySemaphore::try_acquire_until(
47     chrono::SystemClock::time_point deadline) {
48   // Note that if this deadline is in the future, it will get rounded up by
49   // one whole tick due to how try_acquire_for is implemented.
50   return try_acquire_for(deadline - chrono::SystemClock::now());
51 }
52 
native_handle()53 inline BinarySemaphore::native_handle_type BinarySemaphore::native_handle() {
54   return native_type_;
55 }
56 
57 }  // namespace pw::sync
58