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