xref: /aosp_15_r20/external/pigweed/pw_sync_zephyr/binary_semaphore.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
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 
15 #include "pw_sync/binary_semaphore.h"
16 
17 #include <zephyr/kernel.h>
18 
19 namespace pw::sync {
20 
try_acquire_for(chrono::SystemClock::duration timeout)21 bool BinarySemaphore::try_acquire_for(chrono::SystemClock::duration timeout) {
22   // Use non-blocking try_acquire for negative and zero length durations.
23   if (timeout <= chrono::SystemClock::duration::zero()) {
24     return try_acquire();
25   }
26 
27 #ifndef CONFIG_TIMEOUT_64BIT
28   constexpr chrono::SystemClock::duration kMaxTimeoutMinusOne =
29       chrono::SystemClock::duration(K_FOREVER.ticks - 1);
30 
31   while (timeout > kMaxTimeoutMinusOne) {
32     if (k_sem_take(&native_type_, K_TICKS(kMaxTimeoutMinusOne.count())) == 0) {
33       return true;
34     }
35     timeout -= kMaxTimeoutMinusOne;
36   }
37 #endif  // CONFIG_TIMEOUT_64BIT
38 
39   return k_sem_take(&native_type_, K_TICKS(timeout.count())) == 0;
40 }
41 
42 }  // namespace pw::sync
43