blocking_counter_test.cc 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 "absl/synchronization/blocking_counter.h"
  15. #include <thread> // NOLINT(build/c++11)
  16. #include <vector>
  17. #include "gtest/gtest.h"
  18. #include "absl/time/clock.h"
  19. #include "absl/time/time.h"
  20. namespace absl {
  21. ABSL_NAMESPACE_BEGIN
  22. namespace {
  23. void PauseAndDecreaseCounter(BlockingCounter* counter, int* done) {
  24. absl::SleepFor(absl::Seconds(1));
  25. *done = 1;
  26. counter->DecrementCount();
  27. }
  28. TEST(BlockingCounterTest, BasicFunctionality) {
  29. // This test verifies that BlockingCounter functions correctly. Starts a
  30. // number of threads that just sleep for a second and decrement a counter.
  31. // Initialize the counter.
  32. const int num_workers = 10;
  33. BlockingCounter counter(num_workers);
  34. std::vector<std::thread> workers;
  35. std::vector<int> done(num_workers, 0);
  36. // Start a number of parallel tasks that will just wait for a seconds and
  37. // then decrement the count.
  38. workers.reserve(num_workers);
  39. for (int k = 0; k < num_workers; k++) {
  40. workers.emplace_back(
  41. [&counter, &done, k] { PauseAndDecreaseCounter(&counter, &done[k]); });
  42. }
  43. // Wait for the threads to have all finished.
  44. counter.Wait();
  45. // Check that all the workers have completed.
  46. for (int k = 0; k < num_workers; k++) {
  47. EXPECT_EQ(1, done[k]);
  48. }
  49. for (std::thread& w : workers) {
  50. w.join();
  51. }
  52. }
  53. TEST(BlockingCounterTest, WaitZeroInitialCount) {
  54. BlockingCounter counter(0);
  55. counter.Wait();
  56. }
  57. #if GTEST_HAS_DEATH_TEST
  58. TEST(BlockingCounterTest, WaitNegativeInitialCount) {
  59. EXPECT_DEATH(BlockingCounter counter(-1),
  60. "BlockingCounter initial_count negative");
  61. }
  62. #endif
  63. } // namespace
  64. ABSL_NAMESPACE_END
  65. } // namespace absl