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 "RTOS.h" 17 #include "pw_assert/assert.h" 18 #include "pw_chrono/system_clock.h" 19 #include "pw_chrono_embos/system_clock_constants.h" 20 #include "pw_interrupt/context.h" 21 #include "pw_sync/binary_semaphore.h" 22 23 namespace pw::sync { 24 BinarySemaphore()25inline BinarySemaphore::BinarySemaphore() : native_type_() { 26 OS_CreateCSema(&native_type_, 0); 27 } 28 ~BinarySemaphore()29inline BinarySemaphore::~BinarySemaphore() { OS_DeleteCSema(&native_type_); } 30 release()31inline void BinarySemaphore::release() { OS_SignalCSemaMax(&native_type_, 1); } 32 acquire()33inline void BinarySemaphore::acquire() { 34 // Enforce the pw::sync::BinarySemaphore IRQ contract. 35 PW_DASSERT(!interrupt::InInterruptContext()); 36 OS_WaitCSema(&native_type_); 37 } 38 try_acquire()39inline bool BinarySemaphore::try_acquire() noexcept { 40 return OS_CSemaRequest(&native_type_) != 0; 41 } 42 try_acquire_until(chrono::SystemClock::time_point deadline)43inline bool BinarySemaphore::try_acquire_until( 44 chrono::SystemClock::time_point deadline) { 45 // Note that if this deadline is in the future, it will get rounded up by 46 // one whole tick due to how try_acquire_for is implemented. 47 return try_acquire_for(deadline - chrono::SystemClock::now()); 48 } 49 native_handle()50inline BinarySemaphore::native_handle_type BinarySemaphore::native_handle() { 51 return native_type_; 52 } 53 54 } // namespace pw::sync 55