Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created September 20, 2018 00:30
Show Gist options
  • Save goldsborough/1123ee6599a3b46c06c2c6d3d1213117 to your computer and use it in GitHub Desktop.
Save goldsborough/1123ee6599a3b46c06c2c6d3d1213117 to your computer and use it in GitHub Desktop.
C++ semaphore
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