Dune-Fufem 2.11-git
Loading...
Searching...
No Matches
barrier.hh
Go to the documentation of this file.
1// -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2// vi: set et ts=4 sw=2 sts=2:
3
4// SPDX-FileCopyrightText: Copyright © DUNE-FUFEM Project contributors, see file AUTHORS.md
5// SPDX-License-Identifier: LicenseRef-GPL-2.0-only-with-DUNE-exception OR LGPL-3.0-or-later
6
7#ifndef DUNE_FUFEM_PARALLEL_BARRIER_HH
8#define DUNE_FUFEM_PARALLEL_BARRIER_HH
9
10#include <cstddef>
11#include <mutex>
12#include <condition_variable>
13
14
15
16namespace Dune {
17namespace Fufem {
18
19
30class Barrier {
31public:
32
34 safedCount_(count), remaining_(count), phase_(0)
35 {}
36
38 {
39 // Acquire lock for writing to shared counter remaining_.
40 auto l = std::unique_lock(mut);
41 --remaining_;
42 if (remaining_ != 0)
43 {
44 // If we're not the last thread to arrive:
45 // Wait until all thread have been notified by the last one.
46 // To avoid lost or spurious wake-ups one should always use
47 // a condition.
48 auto myphase = phase_+1;
49 cv.wait(l, [&]{ return myphase <= phase_; });
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 remaining_ = safedCount_;
57 ++phase_;
58 cv.notify_all();
59 }
60 }
61
62private:
63 mutable std::mutex mut;
65 std::size_t safedCount_;
66 std::ptrdiff_t remaining_;
67 std::ptrdiff_t phase_ = 0;
68};
69
70
71
72} // namespace Fufem
73} // namespace Dune
74
75
76#endif // DUNE_FUFEM_PARALLEL_BARRIER_HH
77
A barrier primitive for multi-threaded code.
Definition barrier.hh:30
Barrier(std::size_t count)
Definition barrier.hh:33
void arrive_and_wait()
Definition barrier.hh:37