ChimeraTK-cppext 01.05.02
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
7#include <mutex>
8
9namespace cppext {
10
11 class barrier {
12 public:
13 barrier(size_t nThreads) : _count(nThreads), _nThreads(nThreads) {}
14
15 void wait() {
16 std::unique_lock<decltype(_mutex)> lock(_mutex);
17 assert(_count > 0);
18 --_count;
19 if(_count == 0) {
20 _barrierReached = true;
21 _condition.notify_all();
22 _count = _nThreads;
23 }
24 else {
25 _barrierReached = false;
26 while(!_barrierReached) _condition.wait(lock);
27 }
28 }
29
30 private:
31 // mutex required for the condition variable to work
32 std::mutex _mutex;
33
34 // condition variable used for notification
35 std::condition_variable _condition;
36
37 // barrier counter
38 size_t _count;
39
40 // flag if barrier is reached by all threads
41 bool _barrierReached{false};
42
43 // number of threads
44 size_t _nThreads;
45 };
46
47} // namespace cppext
barrier(size_t nThreads)
Definition barrier.hpp:13