From: Brian Norris Date: Tue, 9 Oct 2012 18:15:36 +0000 (-0700) Subject: barrier: add hand-written barrier implementation X-Git-Tag: pldi2013~65 X-Git-Url: http://demsky.eecs.uci.edu/git/?p=model-checker-benchmarks.git;a=commitdiff_plain;h=1acf3219e49d5194740cc600a76e68962fbdce6f barrier: add hand-written barrier implementation Grabbed from: http://stackoverflow.com/questions/8115267/writing-a-spinning-thread-barrier-using-c11-atomics --- 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_; +};