loon
High-performance header-only C++ library for low-latency applications
Loading...
Searching...
No Matches
spsc.hpp
1#include <atomic>
2#include <cstddef>
3
4namespace loon {
5
11template <typename T, size_t N>
12class SpscQueue {
13 public:
18 SpscQueue() : capacity_(N + 1) {}
19
27 bool push(const T& value) {
28 auto tail = tail_.load(std::memory_order_relaxed);
29 auto head = head_.load(std::memory_order_acquire);
30 if ((tail + 1) % capacity_ == head) {
31 return false;
32 }
33
34 data_[tail] = value;
35 tail_.store((tail + 1) % capacity_, std::memory_order_release);
36 return true;
37 }
38
48 bool pop(T& value) {
49 auto tail = tail_.load(std::memory_order_acquire);
50 auto head = head_.load(std::memory_order_relaxed);
51 if (tail == head) {
52 return false;
53 }
54
55 value = data_[head];
56 head_.store((head_ + 1) % capacity_, std::memory_order_release);
57 return true;
58 }
59
63 size_t capacity() const { return capacity_ - 1; }
64
67 bool empty() const { return head_ == tail_; }
68
71 bool full() const {
72 return (tail_.load(std::memory_order_acquire) + 1) % capacity_ ==
73 head_.load(std::memory_order_acquire);
74 }
75
76 private:
77 size_t capacity_{0};
78 T data_[N + 1];
79 std::atomic<size_t> head_{0};
80 std::atomic<size_t> tail_{0};
81};
82
83} // namespace loon
A lock-free single-producer single-consumer (SPSC) queue with fixed capacity.
Definition spsc.hpp:12
bool full() const
Checks if the queue is full.
Definition spsc.hpp:71
bool empty() const
Checks if the queue is empty.
Definition spsc.hpp:67
size_t capacity() const
Returns the maximum number of elements the queue can hold.
Definition spsc.hpp:63