ChimeraTK-cppext 01.07.01
Loading...
Searching...
No Matches
barrier.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Deutsches Elektronen-Synchrotron DESY, MSK, ChimeraTK Project <chimeratk-support@desy.de>
2// SPDX-License-Identifier: LGPL-3.0-or-later
3#pragma once
4
5#include <condition_variable>
6#include <mutex>
7
8namespace cppext {
9
10 class barrier {
11 public:
12 barrier(size_t nThreads) : _count(nThreads), _nThreads(nThreads) {}
13
14 void wait() {
15 std::unique_lock<decltype(_mutex)> lock(_mutex);
16 assert(_count > 0);
17 --_count;
18 if(_count == 0) {
19 _barrierReached = true;
20 _condition.notify_all();
21 _count = _nThreads;
22 }
23 else {
24 _barrierReached = false;
25 while(!_barrierReached) _condition.wait(lock);
26 }
27 }
28
29 private:
30 // mutex required for the condition variable to work
31 std::mutex _mutex;
32
33 // condition variable used for notification
34 std::condition_variable _condition;
35
36 // barrier counter
37 size_t _count;
38
39 // flag if barrier is reached by all threads
40 bool _barrierReached{false};
41
42 // number of threads
43 size_t _nThreads;
44 };
45
46} // namespace cppext
barrier(size_t nThreads)
Definition barrier.hpp:12