1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of 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,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "absl/synchronization/blocking_counter.h"
16
17 #include <atomic>
18
19 #include "absl/base/internal/raw_logging.h"
20
21 namespace absl {
22 ABSL_NAMESPACE_BEGIN
23
24 namespace {
25
26 // Return whether int *arg is true.
IsDone(void * arg)27 bool IsDone(void *arg) { return *reinterpret_cast<bool *>(arg); }
28
29 } // namespace
30
BlockingCounter(int initial_count)31 BlockingCounter::BlockingCounter(int initial_count)
32 : count_(initial_count),
33 num_waiting_(0),
34 done_{initial_count == 0 ? true : false} {
35 ABSL_RAW_CHECK(initial_count >= 0, "BlockingCounter initial_count negative");
36 }
37
DecrementCount()38 bool BlockingCounter::DecrementCount() {
39 int count = count_.fetch_sub(1, std::memory_order_acq_rel) - 1;
40 ABSL_RAW_CHECK(count >= 0,
41 "BlockingCounter::DecrementCount() called too many times");
42 if (count == 0) {
43 MutexLock l(&lock_);
44 done_ = true;
45 return true;
46 }
47 return false;
48 }
49
Wait()50 void BlockingCounter::Wait() {
51 MutexLock l(&this->lock_);
52
53 // only one thread may call Wait(). To support more than one thread,
54 // implement a counter num_to_exit, like in the Barrier class.
55 ABSL_RAW_CHECK(num_waiting_ == 0, "multiple threads called Wait()");
56 num_waiting_++;
57
58 this->lock_.Await(Condition(IsDone, &this->done_));
59
60 // At this point, we know that all threads executing DecrementCount
61 // will not touch this object again.
62 // Therefore, the thread calling this method is free to delete the object
63 // after we return from this method.
64 }
65
66 ABSL_NAMESPACE_END
67 } // namespace absl
68