Samchon Framework for CPP  1.0.0
Semaphore.cpp
1 #include <samchon/library/Semaphore.hpp>
2 
3 #include <atomic>
4 #include <mutex>
5 
6 using namespace std;
7 using namespace samchon::library;
8 
9 /* ====================================================
10  CONSTRUCTORS
11 ==================================================== */
12 Semaphore::Semaphore(size_t size)
13 {
14  this->size_ = size;
15  this->acquired = 0;
16 
17  mtx = new mutex();
18  countMtx = new mutex();
19 }
20 Semaphore::~Semaphore()
21 {
22  delete mtx;
23  delete countMtx;
24 }
25 
26 void Semaphore::setSize(size_t val)
27 {
28  unique_lock<mutex> uk(*countMtx);
29 
30  this->size_ = val;
31 }
32 
33 /* ====================================================
34  GETTERS
35 ==================================================== */
36 auto Semaphore::size() const -> size_t
37 {
38  return size_;
39 }
40 auto Semaphore::acquiredSize() const -> size_t
41 {
42  unique_lock<mutex> uk(*countMtx);
43 
44  return acquired;
45 }
46 
47 /* ====================================================
48  LOCKERS
49 ==================================================== */
50 void Semaphore::acquire()
51 {
52  unique_lock<mutex> uk(*countMtx);
53 
54  if (++acquired >= size_)
55  {
56  uk.unlock();
57  mtx->lock();
58  }
59 }
60 auto Semaphore::tryAcquire() -> bool
61 {
62  unique_lock<mutex> uk(*countMtx);
63 
64  if (acquired == size_)
65  return false;
66  else
67  {
68  if (++acquired >= size_)
69  return mtx->try_lock();
70 
71  return true;
72  }
73 }
74 
75 void Semaphore::release()
76 {
77  unique_lock<mutex> uk(*countMtx);
78 
79  if (acquired != 0 && --acquired == size_ - 1)
80  mtx->unlock();
81 }
Definition: RWMutex.hpp:4
Package of libraries.
Definition: library.hpp:84