1/* Copyright 2019 Google LLC. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16#include "ruy/blocking_counter.h"
17
18#include "ruy/check_macros.h"
19#include "ruy/wait.h"
20
21namespace ruy {
22
23void BlockingCounter::Reset(int initial_count) {
24 int old_count_value = count_.load(std::memory_order_relaxed);
25 RUY_DCHECK_EQ(old_count_value, 0);
26 (void)old_count_value;
27 count_.store(initial_count, std::memory_order_release);
28}
29
30bool BlockingCounter::DecrementCount() {
31 int old_count_value = count_.fetch_sub(1, std::memory_order_acq_rel);
32 RUY_DCHECK_GT(old_count_value, 0);
33 int count_value = old_count_value - 1;
34 bool hit_zero = (count_value == 0);
35 if (hit_zero) {
36 std::lock_guard<std::mutex> lock(count_mutex_);
37 count_cond_.notify_all();
38 }
39 return hit_zero;
40}
41
42void BlockingCounter::Wait(const Duration spin_duration) {
43 const auto& condition = [this]() {
44 return count_.load(std::memory_order_acquire) == 0;
45 };
46 ruy::Wait(condition, spin_duration, &count_cond_, &count_mutex_);
47}
48
49} // namespace ruy
50