Ewout van Bekkum | 9618d8a | 2020-11-09 12:46:52 -0800 | [diff] [blame] | 1 | // Copyright 2020 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 | |
Wyatt Hepler | f298de4 | 2021-03-19 15:06:36 -0700 | [diff] [blame] | 17 | #include "pw_assert/check.h" |
Ewout van Bekkum | 9618d8a | 2020-11-09 12:46:52 -0800 | [diff] [blame] | 18 | |
| 19 | using pw::chrono::SystemClock; |
| 20 | |
| 21 | namespace pw::sync { |
| 22 | |
| 23 | void BinarySemaphore::release() { |
| 24 | std::lock_guard lock(native_type_.mutex); |
| 25 | PW_DCHECK_UINT_LT(native_type_.count, BinarySemaphore::max()); |
| 26 | ++native_type_.count; |
| 27 | native_type_.condition.notify_one(); |
| 28 | } |
| 29 | |
| 30 | void BinarySemaphore::acquire() { |
| 31 | std::unique_lock lock(native_type_.mutex); |
| 32 | native_type_.condition.wait(lock, [&] { return native_type_.count != 0; }); |
| 33 | native_type_.count = 0; |
| 34 | } |
| 35 | |
Ewout van Bekkum | 2da13fa | 2021-01-27 16:04:10 -0800 | [diff] [blame] | 36 | bool BinarySemaphore::try_acquire() noexcept { |
Ewout van Bekkum | 9618d8a | 2020-11-09 12:46:52 -0800 | [diff] [blame] | 37 | std::lock_guard lock(native_type_.mutex); |
| 38 | if (native_type_.count != 0) { |
| 39 | native_type_.count = 0; |
| 40 | return true; |
| 41 | } |
| 42 | return false; |
| 43 | } |
| 44 | |
Ewout van Bekkum | 5ff8cc5 | 2021-09-07 15:46:36 -0700 | [diff] [blame] | 45 | bool BinarySemaphore::try_acquire_until(SystemClock::time_point deadline) { |
Ewout van Bekkum | 9618d8a | 2020-11-09 12:46:52 -0800 | [diff] [blame] | 46 | std::unique_lock lock(native_type_.mutex); |
| 47 | if (native_type_.condition.wait_until( |
Ewout van Bekkum | 5ff8cc5 | 2021-09-07 15:46:36 -0700 | [diff] [blame] | 48 | lock, deadline, [&] { return native_type_.count != 0; })) { |
Ewout van Bekkum | 9618d8a | 2020-11-09 12:46:52 -0800 | [diff] [blame] | 49 | native_type_.count = 0; |
| 50 | return true; |
| 51 | } |
| 52 | return false; |
| 53 | } |
| 54 | |
| 55 | } // namespace pw::sync |