dune-assembler 2.12
Loading...
Searching...
No Matches
barrier.hh
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Copyright © DUNE Project contributors, see file AUTHORS.md
2// SPDX-License-Identifier: LicenseRef-GPL-2.0-only-with-DUNE-exception OR LGPL-3.0-or-later
3
4#ifndef DUNE_ASSEMBLER_PARALLEL_BARRIER_HH
5#define DUNE_ASSEMBLER_PARALLEL_BARRIER_HH
6
7#include <condition_variable>
8#include <cstddef>
9#include <mutex>
10
12
13
24class Barrier {
25public:
26
28 : safedCount_(count)
29 , waitingForCount_(count)
30 , currentPhase_(0)
31 {}
32
34 {
35 // Acquire lock for writing to shared counter waitingForCount_.
36 auto lock = std::unique_lock(mutex_);
37 --waitingForCount_;
38 if (waitingForCount_ != 0)
39 {
40 // If we're not the last thread to arrive:
41 // Wait until all thread have been notified by the last one.
42 // To avoid lost or spurious wake-ups one should always use
43 // a condition. Notice that we deliberately check b-a <= 0
44 // instead of b<=a. In the (unlikely) case of an overflow b
45 // becomes negative such that b<=a evaluates to true even
46 // if a was not incremented. In contrast, b-a will correctly
47 // be computed as 1 or 0 since two overflow events cancel out.
48 auto myPhase = currentPhase_+1;
49 cv_.wait(lock, [&] { return myPhase - currentPhase_ <= 0; });
50 }
51 else
52 {
53 // If we're the last thread to arrive:
54 // Reset counter, proceed to next phase to provide a checkable condition
55 // for the other threads and notify them that we're done.
56 waitingForCount_ = safedCount_;
57 ++currentPhase_;
58 cv_.notify_all();
59 }
60 }
61
62private:
63 std::mutex mutex_;
65 std::size_t safedCount_;
66 std::ptrdiff_t waitingForCount_;
67 std::ptrdiff_t currentPhase_;
68};
69
70
71
72
73} // end namespace Dune::Assembler::Experimental
74
75#endif // DUNE_ASSEMBLER_PARALLEL_BARRIER_HH
Definition barrier.hh:11
A barrier primitive for multi-threaded code.
Definition barrier.hh:24
Barrier(std::size_t count)
Definition barrier.hh:27
void arrive_and_wait()
Definition barrier.hh:33