Created
September 20, 2018 00:30
-
-
Save goldsborough/1123ee6599a3b46c06c2c6d3d1213117 to your computer and use it in GitHub Desktop.
C++ semaphore
This file contains hidden or 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
class Semaphore { | |
public: | |
void post() { | |
std::lock_guard<std::mutex> lock(mutex_); | |
count_ += 1; | |
cv_.notify_one(); | |
} | |
void shutdown() { | |
std::lock_guard<std::mutex> lock(mutex_); | |
cv_.notify_all(); | |
count_ = 0; | |
} | |
template<typename Predicate> | |
void wait(Predicate predicate) { | |
std::unique_lock<std::mutex> lock(mutex_); | |
cv_.wait(lock, [this, predicate]{ return predicate() || count_ > 0; }); | |
if (count_ > 0) { | |
--count_; | |
} | |
} | |
private: | |
size_t count_{0}; | |
std::condition_variable cv_; | |
std::mutex mutex_; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment