blocking_counter_test.cc
Go to the documentation of this file.
00001 // Copyright 2017 The Abseil Authors.
00002 //
00003 // Licensed under the Apache License, Version 2.0 (the "License");
00004 // you may not use this file except in compliance with the License.
00005 // You may obtain a copy of the License at
00006 //
00007 //      https://www.apache.org/licenses/LICENSE-2.0
00008 //
00009 // Unless required by applicable law or agreed to in writing, software
00010 // distributed under the License is distributed on an "AS IS" BASIS,
00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00012 // See the License for the specific language governing permissions and
00013 // limitations under the License.
00014 
00015 #include "absl/synchronization/blocking_counter.h"
00016 
00017 #include <thread>  // NOLINT(build/c++11)
00018 #include <vector>
00019 
00020 #include "gtest/gtest.h"
00021 #include "absl/time/clock.h"
00022 #include "absl/time/time.h"
00023 
00024 namespace absl {
00025 namespace {
00026 
00027 void PauseAndDecreaseCounter(BlockingCounter* counter, int* done) {
00028   absl::SleepFor(absl::Seconds(1));
00029   *done = 1;
00030   counter->DecrementCount();
00031 }
00032 
00033 TEST(BlockingCounterTest, BasicFunctionality) {
00034   // This test verifies that BlockingCounter functions correctly. Starts a
00035   // number of threads that just sleep for a second and decrement a counter.
00036 
00037   // Initialize the counter.
00038   const int num_workers = 10;
00039   BlockingCounter counter(num_workers);
00040 
00041   std::vector<std::thread> workers;
00042   std::vector<int> done(num_workers, 0);
00043 
00044   // Start a number of parallel tasks that will just wait for a seconds and
00045   // then decrement the count.
00046   workers.reserve(num_workers);
00047   for (int k = 0; k < num_workers; k++) {
00048     workers.emplace_back(
00049         [&counter, &done, k] { PauseAndDecreaseCounter(&counter, &done[k]); });
00050   }
00051 
00052   // Wait for the threads to have all finished.
00053   counter.Wait();
00054 
00055   // Check that all the workers have completed.
00056   for (int k = 0; k < num_workers; k++) {
00057     EXPECT_EQ(1, done[k]);
00058   }
00059 
00060   for (std::thread& w : workers) {
00061     w.join();
00062   }
00063 }
00064 
00065 }  // namespace
00066 }  // namespace absl


abseil_cpp
Author(s):
autogenerated on Wed Jun 19 2019 19:42:14