CppCommon  1.0.4.1
C++ Common Library
spsc_ring_buffer.h
Go to the documentation of this file.
1 
9 #ifndef CPPCOMMON_THREADS_SPSC_RING_BUFFER_H
10 #define CPPCOMMON_THREADS_SPSC_RING_BUFFER_H
11 
12 #include <atomic>
13 #include <cassert>
14 #include <cstdio>
15 #include <cstring>
16 
17 namespace CppCommon {
18 
20 
33 {
34 public:
36 
39  explicit SPSCRingBuffer(size_t capacity);
40  SPSCRingBuffer(const SPSCRingBuffer&) = delete;
42  ~SPSCRingBuffer() { delete[] _buffer; }
43 
46 
48  explicit operator bool() const noexcept { return !empty(); }
49 
51  bool empty() const noexcept { return (size() == 0); }
53  size_t capacity() const noexcept { return _capacity; }
55  size_t size() const noexcept;
56 
58 
68  bool Enqueue(const void* data, size_t size);
69 
71 
80  bool Dequeue(void* data, size_t& size);
81 
82 private:
83  typedef char cache_line_pad[128];
84 
85  cache_line_pad _pad0;
86  const size_t _capacity;
87  const size_t _mask;
88  uint8_t* const _buffer;
89 
90  cache_line_pad _pad1;
91  std::atomic<size_t> _head;
92  cache_line_pad _pad2;
93  std::atomic<size_t> _tail;
94  cache_line_pad _pad3;
95 };
96 
99 } // namespace CppCommon
100 
101 #include "spsc_ring_buffer.inl"
102 
103 #endif // CPPCOMMON_THREADS_SPSC_RING_BUFFER_H
Single producer / single consumer wait-free ring buffer.
SPSCRingBuffer(SPSCRingBuffer &&)=delete
SPSCRingBuffer & operator=(const SPSCRingBuffer &)=delete
SPSCRingBuffer(const SPSCRingBuffer &)=delete
bool Enqueue(const void *data, size_t size)
Enqueue a data into the ring buffer (single producer thread method)
SPSCRingBuffer & operator=(SPSCRingBuffer &&)=delete
size_t size() const noexcept
Get ring buffer size in bytes.
bool Dequeue(void *data, size_t &size)
Dequeue a data from the ring buffer (single consumer thread method)
size_t capacity() const noexcept
Get ring buffer capacity in bytes.
bool empty() const noexcept
Is ring buffer empty?
SPSCRingBuffer(size_t capacity)
Default class constructor.
C++ Common project definitions.
Definition: token_bucket.h:15