ctrl-utils
semaphore.h
1 
10 #ifndef CTRL_UTILS_SEMAPHORE_H_
11 #define CTRL_UTILS_SEMAPHORE_H_
12 
13 #include <condition_variable> // std::condition_variable
14 #include <mutex> // std::mutex, std::unique_lock
15 
16 namespace std {
17 
19  public:
20  explicit binary_semaphore(bool desired) : val_(desired) {}
21 
22  inline void acquire() {
23  std::unique_lock<std::mutex> lock(m_);
24  cv_.wait(lock, [this]() { return val_; });
25  val_ = false;
26  }
27 
28  bool try_acquire() {
29  std::unique_lock<std::mutex> try_lock(m_, std::try_to_lock);
30  if (!try_lock) return false;
31  val_ = false;
32  return true;
33  }
34 
35  inline void release() {
36  std::unique_lock<std::mutex> lock(m_);
37  val_ = true;
38  lock.unlock();
39  cv_.notify_one();
40  }
41 
42  private:
43  std::condition_variable cv_;
44  std::mutex m_;
45  bool val_ = false;
46 };
47 
49  public:
50  explicit counting_semaphore(ptrdiff_t desired) : val_(desired) {}
51 
52  inline void acquire() {
53  std::unique_lock<std::mutex> lock(m_);
54  cv_.wait(lock, [this]() { return val_ > 0; });
55  --val_;
56  }
57 
58  bool try_acquire() {
59  std::unique_lock<std::mutex> try_lock(m_, std::try_to_lock);
60  if (!try_lock) return false;
61  --val_;
62  return true;
63  }
64 
65  inline void release() {
66  std::unique_lock<std::mutex> lock(m_);
67  ++val_;
68  lock.unlock();
69  cv_.notify_one();
70  }
71 
72  private:
73  std::condition_variable cv_;
74  std::mutex m_;
75  ptrdiff_t val_ = 0;
76 };
77 
78 } // namespace std
79 
80 #endif // CTRL_UTILS_SEMAPHORE_H_
Definition: semaphore.h:18
Definition: semaphore.h:48
Definition: chrono.h:15