1 // Copyright 2020 The Pigweed Authors
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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
16 #include "pw_assert/light.h"
17 #include "pw_chrono/system_clock.h"
18 #include "pw_interrupt/context.h"
19 #include "pw_sync/binary_semaphore.h"
25 inline constexpr char kBinarySemaphoreName[] = "pw::BinarySemaphore";
27 } // namespace backend
29 inline BinarySemaphore::BinarySemaphore() : native_type_() {
31 tx_semaphore_create(&native_type_,
32 const_cast<char*>(backend::kBinarySemaphoreName),
36 inline BinarySemaphore::~BinarySemaphore() {
37 PW_ASSERT(tx_semaphore_delete(&native_type_) == TX_SUCCESS);
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);
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);
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) {
58 PW_ASSERT(result == TX_SUCCESS);
62 inline bool BinarySemaphore::try_acquire_until(
63 chrono::SystemClock::time_point until_at_least) {
64 return try_acquire_for(until_at_least - chrono::SystemClock::now());
67 inline BinarySemaphore::native_handle_type BinarySemaphore::native_handle() {
71 } // namespace pw::sync