ST_engine  0.3-ALPHA
semaphore.hpp
1 #ifndef SEMAPHORE_DEF
2 #define SEMAPHORE_DEF
3 
4 #include <mutex>
5 #include <condition_variable>
6 
7 class semaphore {
8 private:
9  std::mutex mutex_;
10  std::condition_variable condition_;
11  unsigned long count_ = 0; // Initialized as locked.
12 
13 public:
14  void notify() {
15  std::lock_guard<decltype(mutex_)> lock(mutex_);
16  ++count_;
17  condition_.notify_one();
18  }
19 
20  void wait() {
21  std::unique_lock<decltype(mutex_)> lock(mutex_);
22  while (!count_) { // Handle spurious wake-ups.
23  condition_.wait(lock);
24  }
25  --count_;
26  }
27 
28  bool try_wait() {
29  std::lock_guard<decltype(mutex_)> lock(mutex_);
30  if (count_) {
31  --count_;
32  return true;
33  }
34  return false;
35  }
36 };
37 
38 #endif