• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/counting_semaphore.h"
22 
23 namespace pw::sync {
24 
CountingSemaphore()25 inline CountingSemaphore::CountingSemaphore() : native_type_() {
26   OS_CreateCSema(&native_type_, 0);
27 }
28 
~CountingSemaphore()29 inline CountingSemaphore::~CountingSemaphore() {
30   OS_DeleteCSema(&native_type_);
31 }
32 
acquire()33 inline void CountingSemaphore::acquire() {
34   // Enforce the pw::sync::CountingSemaphore IRQ contract.
35   PW_DASSERT(!interrupt::InInterruptContext());
36   OS_WaitCSema(&native_type_);
37 }
38 
try_acquire()39 inline bool CountingSemaphore::try_acquire() noexcept {
40   return OS_CSemaRequest(&native_type_) != 0;
41 }
42 
try_acquire_until(chrono::SystemClock::time_point deadline)43 inline bool CountingSemaphore::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 
50 inline CountingSemaphore::native_handle_type
native_handle()51 CountingSemaphore::native_handle() {
52   return native_type_;
53 }
54 
55 }  // namespace pw::sync
56