Samchon Framework for CPP  1.0.0
Semaphore.hpp
1 #pragma once
2 
3 #include <atomic>
4 #include <mutex>
5 
6 namespace samchon
7 {
8 namespace library
9 {
47  class Semaphore
48  {
49  private:
54  size_t capacity_;
55 
56  /* ====================================================
57  VARIABLES FOR LOCK
58  ==================================================== */
62  size_t acquired_;
63 
64  std::mutex count_mtx;
65 
70  std::mutex mtx;
71 
72  public:
78  Semaphore(size_t capacity = 2)
79  {
80  this->acquired_ = 0;
81  this->capacity_ = capacity;
82  };
83 
88  void setCapacity(size_t val)
89  {
90  std::unique_lock<std::mutex> uk(count_mtx);
91 
92  this->capacity_ = val;
93  };
94 
95  /* ====================================================
96  GETTERS
97  ==================================================== */
104  auto capacity() const -> size_t
105  {
106  return capacity_;
107  };
108 
112  auto acquired() const -> size_t
113  {
114  return acquired_;
115  };
116 
117  /* ====================================================
118  LOCKERS
119  ==================================================== */
128  void acquire()
129  {
130  std::unique_lock<std::mutex> uk(count_mtx);
131 
132  if (++acquired_ == capacity_)
133  {
134  uk.unlock();
135  mtx.lock();
136  }
137  };
138 
152  auto tryAcquire() -> bool
153  {
154  std::unique_lock<std::mutex> uk(count_mtx);
155 
156  if (acquired_ == capacity_)
157  return false;
158  else
159  {
160  if (++acquired_ >= capacity_)
161  return mtx.try_lock();
162 
163  return true;
164  }
165  };
166 
174  void release()
175  {
176  std::unique_lock<std::mutex> uk(count_mtx);
177 
178  if (acquired_ != 0 && --acquired_ == capacity_ - 1)
179  mtx.unlock();
180  };
181  };
182 };
183 };
184 
185 #include <samchon/library/UniqueAcquire.hpp>
186 #include <samchon/library/SharedAcquire.hpp>
auto acquired() const -> size_t
Get acquired size.
Definition: Semaphore.hpp:112
std::mutex mtx
Locker.
Definition: Semaphore.hpp:70
void setCapacity(size_t val)
Set size.
Definition: Semaphore.hpp:88
size_t acquired_
Acquired count.
Definition: Semaphore.hpp:62
Semaphore(size_t capacity=2)
Definition: Semaphore.hpp:78
void acquire()
Acquire admission.
Definition: Semaphore.hpp:128
auto capacity() const -> size_t
Get size.
Definition: Semaphore.hpp:104
size_t capacity_
The size.
Definition: Semaphore.hpp:54
auto tryAcquire() -> bool
Try to acquire admission.
Definition: Semaphore.hpp:152
void release()
Release an admission.
Definition: Semaphore.hpp:174