CppCommon  1.0.4.1
C++ Common Library
mpmc_ring_queue.h
Go to the documentation of this file.
1 
9 #ifndef CPPCOMMON_THREADS_MPMC_RING_QUEUE_H
10 #define CPPCOMMON_THREADS_MPMC_RING_QUEUE_H
11 
12 #include <atomic>
13 #include <cassert>
14 #include <cstdio>
15 #include <cstring>
16 #include <utility>
17 
18 namespace CppCommon {
19 
21 
32 template<typename T>
34 {
35 public:
37 
40  explicit MPMCRingQueue(size_t capacity);
41  MPMCRingQueue(const MPMCRingQueue&) = delete;
43  ~MPMCRingQueue() { delete[] _buffer; }
44 
47 
49  explicit operator bool() const noexcept { return !empty(); }
50 
52  bool empty() const noexcept { return (size() == 0); }
54  size_t capacity() const noexcept { return _capacity; }
56  size_t size() const noexcept;
57 
59 
67  bool Enqueue(const T& item);
69 
77  bool Enqueue(T&& item);
78 
80 
88  bool Dequeue(T& item);
89 
90 private:
91  struct Node
92  {
93  std::atomic<size_t> sequence;
94  T value;
95  };
96 
97  typedef char cache_line_pad[128];
98 
99  cache_line_pad _pad0;
100  const size_t _capacity;
101  const size_t _mask;
102  Node* const _buffer;
103 
104  cache_line_pad _pad1;
105  std::atomic<size_t> _head;
106  cache_line_pad _pad2;
107  std::atomic<size_t> _tail;
108  cache_line_pad _pad3;
109 };
110 
113 } // namespace CppCommon
114 
115 #include "mpmc_ring_queue.inl"
116 
117 #endif // CPPCOMMON_THREADS_MPMC_RING_QUEUE_H
Multiple producers / multiple consumers wait-free ring queue.
MPMCRingQueue(MPMCRingQueue &&)=delete
MPMCRingQueue & operator=(const MPMCRingQueue &)=delete
MPMCRingQueue(const MPMCRingQueue &)=delete
size_t size() const noexcept
Get ring queue size.
MPMCRingQueue & operator=(MPMCRingQueue &&)=delete
size_t capacity() const noexcept
Get ring queue capacity.
bool Enqueue(const T &item)
Enqueue an item into the ring queue (multiple producers threads method)
bool Dequeue(T &item)
Dequeue an item from the ring queue (multiple consumers threads method)
MPMCRingQueue(size_t capacity)
Default class constructor.
bool empty() const noexcept
Is ring queue empty?
Multiple producers / multiple consumers wait-free ring queue inline implementation.
C++ Common project definitions.
Definition: token_bucket.h:15