CppCommon  1.0.4.1
C++ Common Library
mpsc_ring_buffer.h
Go to the documentation of this file.
1 
9 #ifndef CPPCOMMON_THREADS_MPSC_RING_BUFFER_H
10 #define CPPCOMMON_THREADS_MPSC_RING_BUFFER_H
11 
12 #include "threads/spin_lock.h"
14 #include "time/timestamp.h"
15 
16 #include <cstdio>
17 #include <memory>
18 #include <thread>
19 #include <vector>
20 
21 namespace CppCommon {
22 
24 
36 {
37 public:
39 
43  explicit MPSCRingBuffer(size_t capacity, size_t concurrency = std::thread::hardware_concurrency());
44  MPSCRingBuffer(const MPSCRingBuffer&) = delete;
46  ~MPSCRingBuffer() = default;
47 
50 
52  explicit operator bool() const noexcept { return !empty(); }
53 
55  bool empty() const noexcept { return (size() == 0); }
57  size_t capacity() const noexcept { return _capacity; }
59  size_t concurrency() const noexcept { return _concurrency; }
61  size_t size() const noexcept;
62 
64 
74  bool Enqueue(const void* data, size_t size);
75 
77 
86  bool Dequeue(void* data, size_t& size);
87 
88 private:
89  struct Producer
90  {
91  SpinLock lock;
92  SPSCRingBuffer buffer;
93 
94  Producer(size_t capacity) : buffer(capacity) {}
95  };
96 
97  size_t _capacity;
98  size_t _concurrency;
99  std::vector<std::shared_ptr<Producer>> _producers;
100  size_t _consumer;
101 };
102 
105 } // namespace CppCommon
106 
107 #include "mpsc_ring_buffer.inl"
108 
109 #endif // CPPCOMMON_THREADS_MPSC_RING_BUFFER_H
Multiple producers / single consumer wait-free ring buffer.
bool empty() const noexcept
Is ring buffer empty?
MPSCRingBuffer & operator=(const MPSCRingBuffer &)=delete
size_t capacity() const noexcept
Get ring buffer capacity.
MPSCRingBuffer(const MPSCRingBuffer &)=delete
MPSCRingBuffer(size_t capacity, size_t concurrency=std::thread::hardware_concurrency())
Default class constructor.
size_t size() const noexcept
Get ring buffer size.
MPSCRingBuffer(MPSCRingBuffer &&)=delete
MPSCRingBuffer & operator=(MPSCRingBuffer &&)=delete
bool Enqueue(const void *data, size_t size)
Enqueue a data into the ring buffer (single producer thread method)
size_t concurrency() const noexcept
Get ring buffer concurrency.
bool Dequeue(void *data, size_t &size)
Dequeue a data from the ring buffer (single consumer thread method)
Single producer / single consumer wait-free ring buffer.
Spin-lock synchronization primitive.
Definition: spin_lock.h:30
Multiple producers / single consumer wait-free ring buffer class inline implementation.
C++ Common project definitions.
Definition: token_bucket.h:15
Spin-lock synchronization primitive definition.
Single producer / single consumer wait-free ring buffer definition.
Timestamp definition.