blocking_counter_test.cc
Go to the documentation of this file.
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 
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 namespace {
26 
27 void PauseAndDecreaseCounter(BlockingCounter* counter, int* done) {
29  *done = 1;
30  counter->DecrementCount();
31 }
32 
33 TEST(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
void SleepFor(absl::Duration duration)
Definition: clock.h:68
TEST(NotificationTest, SanityTest)
int * counter
Definition: algorithm.h:29
constexpr Duration Seconds(int64_t n)
Definition: time.h:1461


abseil_cpp
Author(s):
autogenerated on Tue Jun 18 2019 19:44:35