Basic test implementation that has a group of 'num_threads' threads join the same barrier 'num_iters' times. There is no overlap between the iterations i.e. each group of threads terminates before the next group starts.
| 31 | // same barrier 'num_iters' times. There is no overlap between the iterations i.e. |
| 32 | // each group of threads terminates before the next group starts. |
| 33 | void BasicTest(int num_threads, int num_iters) { |
| 34 | CyclicBarrier barrier(num_threads); |
| 35 | int counter = 0; |
| 36 | for (int i = 0; i < num_iters; ++i) { |
| 37 | thread_group threads; |
| 38 | for (int j = 0; j < num_threads; ++j) { |
| 39 | threads.add_thread(new thread([&]() { |
| 40 | // Add some randomness to test so that threads don't always join in predictable |
| 41 | // order. |
| 42 | SleepForMs(rand() % 5); |
| 43 | EXPECT_OK(barrier.Wait([&counter]() { |
| 44 | ++counter; |
| 45 | return Status::OK(); |
| 46 | })); |
| 47 | })); |
| 48 | } |
| 49 | threads.join_all(); |
| 50 | // Counter should have been incremented by last arriving threads. |
| 51 | EXPECT_EQ(i + 1, counter); |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // Test one iteration of the barrier with varying thread counts. |
| 56 | TEST(CyclicBarrierTest, BasicOneIter) { |