Skip to content

Instantly share code, notes, and snippets.

@romanbsd
Created July 12, 2020 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romanbsd/94c798bf7d709e6ab8414faa349083e3 to your computer and use it in GitHub Desktop.
Save romanbsd/94c798bf7d709e6ab8414faa349083e3 to your computer and use it in GitHub Desktop.
#ifndef __H_BARRIER
#define __H_BARRIER
#include <mutex>
// https://stackoverflow.com/questions/24465533/implementing-boostbarrier-in-c11
class Barrier {
public:
explicit Barrier(std::size_t count) : mThreshold(count), mCount(count), mGeneration(0) {
}
void wait() {
std::unique_lock<std::mutex> lock{mMutex};
auto generation = mGeneration;
if (!--mCount) {
mGeneration++;
mCount = mThreshold;
mCond.notify_all();
} else {
mCond.wait(lock, [this, generation] { return generation != mGeneration; });
}
}
private:
std::mutex mMutex;
std::condition_variable mCond;
std::size_t mThreshold;
std::size_t mCount;
std::size_t mGeneration;
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment