blob: 629d0dc361c92377d30df975eba67413545bff69 [file] [log] [blame]
Ewout van Bekkum9618d8a2020-11-09 12:46:52 -08001// 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/counting_semaphore.h"
16
17#include "pw_assert/assert.h"
18
19using pw::chrono::SystemClock;
20
21namespace pw::sync {
22
23void CountingSemaphore::release(ptrdiff_t update) {
24 PW_DCHECK_UINT_GE(update, 0);
25 {
26 std::lock_guard lock(native_type_.mutex);
27 PW_DCHECK_UINT_LE(update, CountingSemaphore::max() - native_type_.count);
28 native_type_.count += update;
29 native_type_.condition.notify_one();
30 }
31}
32
33void CountingSemaphore::acquire() {
34 std::unique_lock lock(native_type_.mutex);
35 native_type_.condition.wait(lock, [&] { return native_type_.count != 0; });
36 --native_type_.count;
37}
38
Ewout van Bekkum2da13fa2021-01-27 16:04:10 -080039bool CountingSemaphore::try_acquire() noexcept {
Ewout van Bekkum9618d8a2020-11-09 12:46:52 -080040 std::lock_guard lock(native_type_.mutex);
41 if (native_type_.count != 0) {
42 --native_type_.count;
43 return true;
44 }
45 return false;
46}
47
48bool CountingSemaphore::try_acquire_until(
49 SystemClock::time_point until_at_least) {
50 std::unique_lock lock(native_type_.mutex);
51 if (native_type_.condition.wait_until(
52 lock, until_at_least, [&] { return native_type_.count != 0; })) {
53 --native_type_.count;
54 return true;
55 }
56 return false;
57}
58
59} // namespace pw::sync