CppCommon  1.0.4.1
C++ Common Library
spsc_ring_queue.h
Go to the documentation of this file.
1 
9 #ifndef CPPCOMMON_THREADS_SPSC_RING_QUEUE_H
10 #define CPPCOMMON_THREADS_SPSC_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 
33 template<typename T>
35 {
36 public:
38 
41  explicit SPSCRingQueue(size_t capacity);
42  SPSCRingQueue(const SPSCRingQueue&) = delete;
44  ~SPSCRingQueue() { delete[] _buffer; }
45 
48 
50  explicit operator bool() const noexcept { return !empty(); }
51 
53  bool empty() const noexcept { return (size() == 0); }
55  size_t capacity() const noexcept { return _capacity; }
57  size_t size() const noexcept;
58 
60 
68  bool Enqueue(const T& item);
70 
78  bool Enqueue(T&& item);
79 
81 
89  bool Dequeue(T& item);
90 
91 private:
92  typedef char cache_line_pad[128];
93 
94  cache_line_pad _pad0;
95  const size_t _capacity;
96  const size_t _mask;
97  T* const _buffer;
98 
99  cache_line_pad _pad1;
100  std::atomic<size_t> _head;
101  cache_line_pad _pad2;
102  std::atomic<size_t> _tail;
103  cache_line_pad _pad3;
104 };
105 
108 } // namespace CppCommon
109 
110 #include "spsc_ring_queue.inl"
111 
112 #endif // CPPCOMMON_THREADS_SPSC_RING_QUEUE_H
Single producer / single consumer wait-free ring queue.
bool Enqueue(const T &item)
Enqueue an item into the ring queue (single producer thread method)
SPSCRingQueue(const SPSCRingQueue &)=delete
SPSCRingQueue & operator=(SPSCRingQueue &&)=delete
size_t size() const noexcept
Get ring queue size.
bool empty() const noexcept
Is ring queue empty?
size_t capacity() const noexcept
Get ring queue capacity.
SPSCRingQueue & operator=(const SPSCRingQueue &)=delete
SPSCRingQueue(size_t capacity)
Default class constructor.
bool Dequeue(T &item)
Dequeue an item from the ring queue (single consumer thread method)
SPSCRingQueue(SPSCRingQueue &&)=delete
C++ Common project definitions.
Definition: token_bucket.h:15