barrier: add hand-written barrier implementation
authorBrian Norris <banorris@uci.edu>
Tue, 9 Oct 2012 18:15:36 +0000 (11:15 -0700)
committerBrian Norris <banorris@uci.edu>
Tue, 9 Oct 2012 18:15:36 +0000 (11:15 -0700)
Grabbed from:
http://stackoverflow.com/questions/8115267/writing-a-spinning-thread-barrier-using-c11-atomics

barrier/barrier.h [new file with mode: 0644]

diff --git a/barrier/barrier.h b/barrier/barrier.h
new file mode 100644 (file)
index 0000000..871e10f
--- /dev/null
@@ -0,0 +1,33 @@
+#include <atomic>
+
+class spinning_barrier {
+ public:
+       spinning_barrier (unsigned int n) : n_ (n), nwait_ (0), step_(0) {}
+
+       bool wait() {
+               unsigned int step = step_.load ();
+
+               if (nwait_.fetch_add (1) == n_ - 1) {
+                       /* OK, last thread to come.  */
+                       nwait_.store (0); // XXX: maybe can use relaxed ordering here ??
+                       step_.fetch_add (1);
+                       return true;
+               } else {
+                       /* Run in circles and scream like a little girl.  */
+                       while (step_.load () == step)
+                               ;
+                       return false;
+               }
+       }
+
+ protected:
+       /* Number of synchronized threads. */
+       const unsigned int n_;
+
+       /* Number of threads currently spinning.  */
+       std::atomic<unsigned int> nwait_;
+
+       /* Number of barrier syncronizations completed so far, 
+        *      * it's OK to wrap.  */
+       std::atomic<unsigned int> step_;
+};