CppCommon  1.0.4.1
C++ Common Library
seq_lock.inl
Go to the documentation of this file.
1 
9 namespace CppCommon {
10 
11 template <typename T>
12 inline SeqLock<T>::SeqLock() : _seq(0)
13 {
14  memset(_pad0, 0, sizeof(cache_line_pad));
15  memset(_pad1, 0, sizeof(cache_line_pad));
16 }
17 
18 template <typename T>
19 inline SeqLock<T>::SeqLock(const T& data) : SeqLock()
20 {
21  _data = data;
22 }
23 
24 template <typename T>
25 inline SeqLock<T>& SeqLock<T>::operator=(const T& data) noexcept
26 {
27  Write(data);
28  return *this;
29 }
30 
31 template <typename T>
32 inline T SeqLock<T>::Read() const noexcept
33 {
34  T data;
35  size_t seq0;
36  size_t seq1;
37 
38  do
39  {
40  seq0 = _seq.load(std::memory_order_acquire);
41  std::atomic_signal_fence(std::memory_order_acq_rel);
42  data = _data;
43  std::atomic_signal_fence(std::memory_order_acq_rel);
44  seq1 = _seq.load(std::memory_order_acquire);
45  } while ((seq0 != seq1) || (seq0 & 1));
46 
47  return data;
48 }
49 
50 template <typename T>
51 inline void SeqLock<T>::Write(const T& data) noexcept
52 {
53  size_t seq0 = _seq.load(std::memory_order_relaxed);
54  _seq.store(seq0 + 1, std::memory_order_release);
55  std::atomic_signal_fence(std::memory_order_acq_rel);
56  _data = data;
57  std::atomic_signal_fence(std::memory_order_acq_rel);
58  _seq.store(seq0 + 2, std::memory_order_release);
59 }
60 
61 } // namespace CppCommon
Sequential lock synchronization primitive.
Definition: seq_lock.h:31
void Write(const T &data) noexcept
Write data under the sequential lock.
Definition: seq_lock.inl:51
T Read() const noexcept
Read data under the sequential lock.
Definition: seq_lock.inl:32
SeqLock & operator=(const T &data) noexcept
Definition: seq_lock.inl:25
C++ Common project definitions.
Definition: token_bucket.h:15