CppCommon  1.0.4.1
C++ Common Library
mpsc_ring_queue.h
Go to the documentation of this file.
1 
9 #ifndef CPPCOMMON_THREADS_MPSC_RING_QUEUE_H
10 #define CPPCOMMON_THREADS_MPSC_RING_QUEUE_H
11 
12 #include "threads/spin_lock.h"
14 #include "time/timestamp.h"
15 
16 #include <cassert>
17 #include <cstdio>
18 #include <functional>
19 #include <memory>
20 #include <thread>
21 #include <utility>
22 #include <vector>
23 
24 namespace CppCommon {
25 
27 
38 template<typename T>
40 {
41 public:
43 
47  explicit MPSCRingQueue(size_t capacity, size_t concurrency = std::thread::hardware_concurrency());
48  MPSCRingQueue(const MPSCRingQueue&) = delete;
50  ~MPSCRingQueue() = default;
51 
54 
56  explicit operator bool() const noexcept { return !empty(); }
57 
59  bool empty() const noexcept { return (size() == 0); }
61  size_t capacity() const noexcept { return _capacity; }
63  size_t concurrency() const noexcept { return _concurrency; }
65  size_t size() const noexcept;
66 
68 
76  bool Enqueue(const T& item);
78 
86  bool Enqueue(T&& item);
87 
89 
97  bool Dequeue(T& item);
98 
100 
108  bool Dequeue(const std::function<void(const T&)>& handler = [](const int&){});
109 
110 private:
111  struct Producer
112  {
113  SpinLock lock;
114  SPSCRingQueue<T> queue;
115 
116  Producer(size_t capacity) : queue(capacity) {}
117  };
118 
119  size_t _capacity;
120  size_t _concurrency;
121  std::vector<std::shared_ptr<Producer>> _producers;
122  size_t _consumer;
123 };
124 
127 } // namespace CppCommon
128 
129 #include "mpsc_ring_queue.inl"
130 
131 #endif // CPPCOMMON_THREADS_MPSC_RING_QUEUE_H
Multiple producers / single consumer wait-free ring queue.
MPSCRingQueue(MPSCRingQueue &&)=delete
bool Dequeue(T &item)
Dequeue an item from the ring queue (single consumer threads method)
MPSCRingQueue(size_t capacity, size_t concurrency=std::thread::hardware_concurrency())
Default class constructor.
size_t size() const noexcept
Get ring queue size.
MPSCRingQueue(const MPSCRingQueue &)=delete
MPSCRingQueue & operator=(const MPSCRingQueue &)=delete
MPSCRingQueue & operator=(MPSCRingQueue &&)=delete
bool Enqueue(const T &item)
Enqueue an item into the ring queue (multiple producers threads method)
size_t capacity() const noexcept
Get ring queue capacity.
bool empty() const noexcept
Is ring queue empty?
size_t concurrency() const noexcept
Get ring queue concurrency.
Multiple producers / single consumer wait-free ring queue class inline implementation.
C++ Common project definitions.
Definition: token_bucket.h:15
Spin-lock synchronization primitive definition.
Single producer / single consumer wait-free ring queue definition.
Timestamp definition.