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/light.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/counting_semaphore.h" 22 23 namespace pw::sync { 24 CountingSemaphore()25inline CountingSemaphore::CountingSemaphore() : native_type_() { 26 OS_CreateCSema(&native_type_, 0); 27 } 28 ~CountingSemaphore()29inline CountingSemaphore::~CountingSemaphore() { 30 OS_DeleteCSema(&native_type_); 31 } 32 acquire()33inline void CountingSemaphore::acquire() { 34 PW_ASSERT(!interrupt::InInterruptContext()); 35 OS_WaitCSema(&native_type_); 36 } 37 try_acquire()38inline bool CountingSemaphore::try_acquire() noexcept { 39 return OS_CSemaRequest(&native_type_) != 0; 40 } 41 try_acquire_until(chrono::SystemClock::time_point until_at_least)42inline bool CountingSemaphore::try_acquire_until( 43 chrono::SystemClock::time_point until_at_least) { 44 // Note that if this deadline is in the future, it will get rounded up by 45 // one whole tick due to how try_acquire_for is implemented. 46 return try_acquire_for(until_at_least - chrono::SystemClock::now()); 47 } 48 49 inline CountingSemaphore::native_handle_type native_handle()50CountingSemaphore::native_handle() { 51 return native_type_; 52 } 53 54 } // namespace pw::sync 55