Created
July 12, 2020 14:44
-
-
Save romanbsd/94c798bf7d709e6ab8414faa349083e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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