xref: /aosp_15_r20/external/pigweed/pw_sync_threadx/public/pw_sync_threadx/binary_semaphore_inline.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
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/assert.h"
17 #include "pw_chrono/system_clock.h"
18 #include "pw_interrupt/context.h"
19 #include "pw_sync/binary_semaphore.h"
20 #include "tx_api.h"
21 
22 namespace pw::sync {
23 namespace backend {
24 
25 inline constexpr char kBinarySemaphoreName[] = "pw::BinarySemaphore";
26 
27 }  // namespace backend
28 
BinarySemaphore()29 inline BinarySemaphore::BinarySemaphore() : native_type_() {
30   PW_ASSERT(
31       tx_semaphore_create(&native_type_,
32                           const_cast<char*>(backend::kBinarySemaphoreName),
33                           0) == TX_SUCCESS);
34 }
35 
~BinarySemaphore()36 inline BinarySemaphore::~BinarySemaphore() {
37   PW_ASSERT(tx_semaphore_delete(&native_type_) == TX_SUCCESS);
38 }
39 
release()40 inline void BinarySemaphore::release() {
41   // Give at most 1 token.
42   const UINT result = tx_semaphore_ceiling_put(&native_type_, 1);
43   PW_ASSERT(result == TX_SUCCESS || result == TX_CEILING_EXCEEDED);
44 }
45 
acquire()46 inline void BinarySemaphore::acquire() {
47   // Enforce the pw::sync::BinarySemaphore IRQ contract.
48   PW_DASSERT(!interrupt::InInterruptContext());
49   const UINT result = tx_semaphore_get(&native_type_, TX_WAIT_FOREVER);
50   PW_ASSERT(result == TX_SUCCESS);
51 }
52 
try_acquire()53 inline bool BinarySemaphore::try_acquire() noexcept {
54   const UINT result = tx_semaphore_get(&native_type_, TX_NO_WAIT);
55   if (result == TX_NO_INSTANCE) {
56     return false;
57   }
58   PW_ASSERT(result == TX_SUCCESS);
59   return true;
60 }
61 
try_acquire_until(chrono::SystemClock::time_point deadline)62 inline bool BinarySemaphore::try_acquire_until(
63     chrono::SystemClock::time_point deadline) {
64   // Note that if this deadline is in the future, it will get rounded up by
65   // one whole tick due to how try_acquire_for is implemented.
66   return try_acquire_for(deadline - chrono::SystemClock::now());
67 }
68 
native_handle()69 inline BinarySemaphore::native_handle_type BinarySemaphore::native_handle() {
70   return native_type_;
71 }
72 
73 }  // namespace pw::sync
74