CppBenchmark 1.0.5.0
C++ Benchmark Library
Loading...
Searching...
No Matches
barrier.cpp
Go to the documentation of this file.
1
9#include "benchmark/barrier.h"
10
11#include <cassert>
12
13namespace CppBenchmark {
14
15Barrier::Barrier(int threads) noexcept : _counter(threads), _generation(0), _threads(threads)
16{
17 assert((threads > 0) && "Barrier threads counter must be greater than zero!");
18}
19
20bool Barrier::Wait() noexcept
21{
22 std::unique_lock<std::mutex> lock(_mutex);
23
24 // Remember the current barrier generation
25 int generation = _generation;
26
27 // Decrease the count of waiting threads
28 if (--_counter == 0)
29 {
30 // Increase the current barrier generation
31 ++_generation;
32
33 // Reset waiting threads counter
34 _counter = _threads;
35
36 // Notify all waiting threads
37 _cond.notify_all();
38
39 // Notify the last thread that reached the barrier
40 return true;
41 }
42
43 // Wait for the next barrier generation
44 _cond.wait(lock, [&, this]() { return generation != _generation; });
45
46 // Notify each of remaining threads
47 return false;
48}
49
50} // namespace CppBenchmark
Barrier synchronization primitive definition.
Barrier(int threads) noexcept
Default class constructor.
Definition barrier.cpp:15
bool Wait() noexcept
Wait at the barrier until all other threads reach this barrier.
Definition barrier.cpp:20
C++ Benchmark project definitions.
Definition barrier.h:15