XTL  0.1
eXtended Template Library
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
rw_lock.hpp
Go to the documentation of this file.
1 
5 #pragma once
6 
8 
9 namespace xtd{
10  namespace concurrent{
15  template <typename _WaitPolicyT>
16  class rw_lock_base{
17  std::atomic<uint32_t> _lock;
18  static constexpr uint32_t write_lock_bit = 0x80000000;
19  static constexpr uint32_t read_bits_mask = ~write_lock_bit;
20  _WaitPolicyT _WaitPolicy;
21  public:
22  using wait_policy_type = _WaitPolicyT;
23  rw_lock_base(wait_policy_type oWait = wait_policy_type()) : _lock(0), _WaitPolicy(oWait){}
25  uint32_t readers() const{
26  return _lock.load() & read_bits_mask;
27  }
28 
30  void unlock(){
31  forever{
32  auto iOriginal = _lock.load();
33  if (write_lock_bit == iOriginal){
34  _lock.store(0);
35  break;
36  } else{
37  if (_lock.compare_exchange_strong(iOriginal, iOriginal - 1)){
38  break;
39  }
40  }
41  _WaitPolicy();
42  }
43  }
45  void lock_read(){
46  forever{
47  auto iOriginal = _lock.load() & read_bits_mask;
48  if (_lock.compare_exchange_strong(iOriginal, 1 + iOriginal)){
49  break;
50  }
51  _WaitPolicy();
52  }
53  }
57  bool try_lock_read(){
58  auto iOriginal = _lock.load() & read_bits_mask;
59  return _lock.compare_exchange_strong(iOriginal, 1 + iOriginal);
60  }
62  void lock_write(){
63  uint32_t iOriginal = 0;
64  while (!_lock.compare_exchange_strong(iOriginal, write_lock_bit)){
65  _WaitPolicy();
66  }
67  }
72  uint32_t iOriginal = 0;
73  return _lock.compare_exchange_strong(iOriginal, write_lock_bit);
74  }
76  class scope_read{
77  rw_lock_base& _Lock;
78  public:
79  explicit scope_read(rw_lock_base& oLock) : _Lock(oLock){
80  _Lock.lock_read();
81  }
82  ~scope_read(){
83  _Lock.unlock();
84  }
85  };
87  class scope_write{
88  rw_lock_base& _Lock;
89  public:
90  explicit scope_write(rw_lock_base& oLock) : _Lock(oLock){
91  _Lock.lock_write();
92  }
93  ~scope_write(){
94  _Lock.unlock();
95  }
96  };
97  };
98 
100  }
101 }
bool try_lock_write()
attempts to acquire a write lock for exclusive access
Definition: rw_lock.hpp:71
uint32_t readers() const
Returns the number of active read locks.
Definition: rw_lock.hpp:25
shared declarations for the concurrent namespace
A multiple reader/single writer spin lock supports 2^31 simultaneous readers.
Definition: rw_lock.hpp:16
void unlock()
Frees the write lock or decrements the reader count.
Definition: rw_lock.hpp:30
bool try_lock_read()
tries to acquire a shared read lock
Definition: rw_lock.hpp:57
void lock_write()
acquires a write lock for exclusive access
Definition: rw_lock.hpp:62
RAII pattern to acquire and release a write lock.
Definition: rw_lock.hpp:87
RAII pattern to acquire and release a read lock.
Definition: rw_lock.hpp:76
void lock_read()
Acquires a shared read lock.
Definition: rw_lock.hpp:45