barrier_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/barrier.h"
00016 
00017 #include <thread>  // NOLINT(build/c++11)
00018 #include <vector>
00019 
00020 #include "gtest/gtest.h"
00021 #include "absl/synchronization/mutex.h"
00022 #include "absl/time/clock.h"
00023 
00024 
00025 TEST(Barrier, SanityTest) {
00026   constexpr int kNumThreads = 10;
00027   absl::Barrier* barrier = new absl::Barrier(kNumThreads);
00028 
00029   absl::Mutex mutex;
00030   int counter = 0;  // Guarded by mutex.
00031 
00032   auto thread_func = [&] {
00033     if (barrier->Block()) {
00034       // This thread is the last thread to reach the barrier so it is
00035       // responsible for deleting it.
00036       delete barrier;
00037     }
00038 
00039     // Increment the counter.
00040     absl::MutexLock lock(&mutex);
00041     ++counter;
00042   };
00043 
00044   // Start (kNumThreads - 1) threads running thread_func.
00045   std::vector<std::thread> threads;
00046   for (int i = 0; i < kNumThreads - 1; ++i) {
00047     threads.push_back(std::thread(thread_func));
00048   }
00049 
00050   // Give (kNumThreads - 1) threads a chance to reach the barrier.
00051   // This test assumes at least one thread will have run after the
00052   // sleep has elapsed. Sleeping in a test is usually bad form, but we
00053   // need to make sure that we are testing the barrier instead of some
00054   // other synchronization method.
00055   absl::SleepFor(absl::Seconds(1));
00056 
00057   // The counter should still be zero since no thread should have
00058   // been able to pass the barrier yet.
00059   {
00060     absl::MutexLock lock(&mutex);
00061     EXPECT_EQ(counter, 0);
00062   }
00063 
00064   // Start 1 more thread. This should make all threads pass the barrier.
00065   threads.push_back(std::thread(thread_func));
00066 
00067   // All threads should now be able to proceed and finish.
00068   for (auto& thread : threads) {
00069     thread.join();
00070   }
00071 
00072   // All threads should now have incremented the counter.
00073   absl::MutexLock lock(&mutex);
00074   EXPECT_EQ(counter, kNumThreads);
00075 }


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