From 1acf3219e49d5194740cc600a76e68962fbdce6f Mon Sep 17 00:00:00 2001 From: Brian Norris Date: Tue, 9 Oct 2012 11:15:36 -0700 Subject: [PATCH] barrier: add hand-written barrier implementation Grabbed from: http://stackoverflow.com/questions/8115267/writing-a-spinning-thread-barrier-using-c11-atomics --- barrier/barrier.h | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 barrier/barrier.h diff --git a/barrier/barrier.h b/barrier/barrier.h new file mode 100644 index 0000000..871e10f --- /dev/null +++ b/barrier/barrier.h @@ -0,0 +1,33 @@ +#include + +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 nwait_; + + /* Number of barrier syncronizations completed so far, + * * it's OK to wrap. */ + std::atomic step_; +}; -- 2.34.1