Samchon Framework for CPP  1.0.0
SharedReadLock.hpp
1 #pragma once
2 
3 #include <atomic>
4 #include <samchon/library/RWMutex.hpp>
5 
6 namespace samchon
7 {
8 namespace library
9 {
44  {
45  private:
49  const RWMutex *rw_mutex;
50 
54  std::atomic<size_t> *reference;
55 
59  std::atomic<bool> *locked;
60 
61  public:
62  /* -----------------------------------------------------------
63  CONSTRUCTORS
64  ----------------------------------------------------------- */
71  SharedReadLock(const RWMutex &rw_mutex, bool lock = true)
72  {
73  this->rw_mutex = &rw_mutex;
74  this->reference = new std::atomic<size_t>(0);
75  this->locked = new std::atomic<bool>(false);
76 
77  if (lock == true)
78  rw_mutex.readLock();
79  };
80 
85  {
86  obj.reference->operator++();
87 
88  this->rw_mutex = obj.rw_mutex;
89  this->reference = obj.reference;
90  this->locked = obj.locked;
91  };
92 
97  {
98  //MOVE
99  this->rw_mutex = obj.rw_mutex;
100  this->reference = obj.reference;
101  this->locked = obj.locked;
102 
103  //TRUNCATE
104  obj.rw_mutex = nullptr;
105  obj.reference = nullptr;
106  obj.locked = nullptr;
107  };
108 
113  {
114  if (reference == nullptr || reference->operator--() > 0)
115  return;
116 
117  if (locked->load() == true)
118  rw_mutex->readUnlock();
119 
120  delete reference;
121  delete locked;
122  };
123 
124  /* -----------------------------------------------------------
125  LOCKERS
126  ----------------------------------------------------------- */
130  void lock() const
131  {
132  if (locked->load() == true)
133  return;
134 
135  rw_mutex->readLock();
136  locked->store(true);
137  };
138 
142  void unlock() const
143  {
144  if (locked->load() == false)
145  return;
146 
147  rw_mutex->readUnlock();
148  locked->store(false);
149  };
150 
154  //auto tryLock() const -> bool;
155  };
156 };
157 };
Shared lock from a RWMutex.
void readUnlock() const
Unlock of read.
Definition: RWMutex.hpp:90
void unlock() const
Unlock of read.
std::atomic< size_t > * reference
Referencing count sharing same RWMutex.
SharedReadLock(const SharedReadLock &obj)
Copy Constructor.
void readLock() const
Lock on read.
Definition: RWMutex.hpp:67
SharedReadLock(const RWMutex &rw_mutex, bool lock=true)
Construct from RWMutex.
const RWMutex * rw_mutex
Managed RWMutex.
SharedReadLock(SharedReadLock &&obj)
Move Constructor.
std::atomic< bool > * locked
Whether the mutex was locked by SharedReadLock.
void lock() const
Lock on read.
~SharedReadLock()
Default Destructor.