Lumiera  0.pre.03
»edit your freedom«
sync-barrier.hpp
Go to the documentation of this file.
1 /*
2  SYNC-BARRIER.hpp - N-fold synchronisation point with yield-wait
3 
4  Copyright (C) Lumiera.org
5  2023, Hermann Vosseler <Ichthyostega@web.de>
6 
7  This program is free software; you can redistribute it and/or
8  modify it under the terms of the GNU General Public License as
9  published by the Free Software Foundation; either version 2 of
10  the License, or (at your option) any later version.
11 
12  This program is distributed in the hope that it will be useful,
13  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  GNU General Public License for more details.
16 
17  You should have received a copy of the GNU General Public License
18  along with this program; if not, write to the Free Software
19  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 
21 */
22 
23 
49 #ifndef LIB_SYNC_BARRIER_H
50 #define LIB_SYNC_BARRIER_H
51 
52 
53 #include "lib/error.hpp"
54 #include "lib/nocopy.hpp"
55 
56 #include <thread>
57 #include <atomic>
58 
59 
60 namespace lib {
61 
62 
75  {
76  std::atomic_int latch_;
77 
78  public:
80  explicit
81  SyncBarrier (uint nFold =2)
82  : latch_{int(nFold)}
83  {
84  REQUIRE (nFold >= 2, "Pointless to sync less than two participants.");
85  ENSURE (nFold < 100'000, "Danger territory.... sync 100k Threads??");
86  }
87 
88  void
89  sync()
90  {
91  size_t level = latch_.fetch_add(-1, std::memory_order_acq_rel);
92  if (1 < level)
93  do std::this_thread::yield();
94  while (0 < latch_.load (std::memory_order_relaxed));
95  else
96  latch_.store (0, std::memory_order_relaxed);
97  } // prevent spurious calls from wrapping
98  };
99 
100 
101 
102 } // namespace lib
103 #endif /*LIB_SYNC_BARRIER_H*/
Any copy and copy construction prohibited.
Definition: nocopy.hpp:46
Implementation namespace for support and library code.
Mix-Ins to allow or prohibit various degrees of copying and cloning.
Lumiera error handling (C++ interface).
A one time N-fold mutual synchronisation barrier.
SyncBarrier(uint nFold=2)