blocking_counter.cc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. #include "y_absl/synchronization/blocking_counter.h"
  15. #include <atomic>
  16. #include "y_absl/base/internal/raw_logging.h"
  17. namespace y_absl {
  18. Y_ABSL_NAMESPACE_BEGIN
  19. namespace {
  20. // Return whether int *arg is true.
  21. bool IsDone(void *arg) { return *reinterpret_cast<bool *>(arg); }
  22. } // namespace
  23. BlockingCounter::BlockingCounter(int initial_count)
  24. : count_(initial_count),
  25. num_waiting_(0),
  26. done_{initial_count == 0 ? true : false} {
  27. Y_ABSL_RAW_CHECK(initial_count >= 0, "BlockingCounter initial_count negative");
  28. }
  29. bool BlockingCounter::DecrementCount() {
  30. int count = count_.fetch_sub(1, std::memory_order_acq_rel) - 1;
  31. Y_ABSL_RAW_CHECK(count >= 0,
  32. "BlockingCounter::DecrementCount() called too many times");
  33. if (count == 0) {
  34. MutexLock l(&lock_);
  35. done_ = true;
  36. return true;
  37. }
  38. return false;
  39. }
  40. void BlockingCounter::Wait() {
  41. MutexLock l(&this->lock_);
  42. // only one thread may call Wait(). To support more than one thread,
  43. // implement a counter num_to_exit, like in the Barrier class.
  44. Y_ABSL_RAW_CHECK(num_waiting_ == 0, "multiple threads called Wait()");
  45. num_waiting_++;
  46. this->lock_.Await(Condition(IsDone, &this->done_));
  47. // At this point, we know that all threads executing DecrementCount
  48. // will not touch this object again.
  49. // Therefore, the thread calling this method is free to delete the object
  50. // after we return from this method.
  51. }
  52. Y_ABSL_NAMESPACE_END
  53. } // namespace y_absl