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