14 assert((
capacity > 1) &&
"Ring queue capacity must be greater than one!");
15 assert(((
capacity & (
capacity - 1)) == 0) &&
"Ring queue capacity must be a power of two!");
17 memset(_pad0, 0,
sizeof(cache_line_pad));
18 memset(_pad1, 0,
sizeof(cache_line_pad));
19 memset(_pad2, 0,
sizeof(cache_line_pad));
20 memset(_pad3, 0,
sizeof(cache_line_pad));
23 for (
size_t i = 0; i <
capacity; ++i)
24 _buffer[i].sequence.store(i, std::memory_order_relaxed);
30 const size_t head = _head.load(std::memory_order_acquire);
31 const size_t tail = _tail.load(std::memory_order_acquire);
40 return Enqueue(std::forward<T>(temp));
46 size_t head_sequence = _head.load(std::memory_order_relaxed);
50 Node* node = &_buffer[head_sequence & _mask];
51 size_t node_sequence = node->sequence.load(std::memory_order_acquire);
54 int64_t diff = (int64_t)node_sequence - (int64_t)head_sequence;
61 if (_head.compare_exchange_weak(head_sequence, head_sequence + 1, std::memory_order_relaxed))
64 node->value = std::move(item);
67 node->sequence.store(head_sequence + 1, std::memory_order_release);
80 head_sequence = _head.load(std::memory_order_relaxed);
91 size_t tail_sequence = _tail.load(std::memory_order_relaxed);
95 Node* node = &_buffer[tail_sequence & _mask];
96 size_t node_sequence = node->sequence.load(std::memory_order_acquire);
99 int64_t diff = (int64_t)node_sequence - (int64_t)(tail_sequence + 1);
106 if (_tail.compare_exchange_weak(tail_sequence, tail_sequence + 1, std::memory_order_relaxed))
109 item = std::move(node->value);
112 node->sequence.store(tail_sequence + _mask + 1, std::memory_order_release);
124 tail_sequence = _tail.load(std::memory_order_relaxed);
size_t size() const noexcept
Get ring queue size.
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.
C++ Common project definitions.