plcopen 0.22.0
载入中...
搜索中...
未找到
spsc_queue.h
浏览该文件的文档.
1#pragma once
2
3#include <array>
4#include <atomic>
5#include <cstddef>
6
7namespace plcopen::core::rt
8{
9
10template <typename T, std::size_t Capacity>
11class SpscQueue // NOLINT(clang-analyzer-optin.performance.Padding)
12{
13public:
14 static_assert(Capacity > 0, "SpscQueue capacity must be positive");
15
16 bool push(const T &value)
17 {
18 const std::size_t head = head_.load(std::memory_order_relaxed);
19 const std::size_t next = increment(head);
20 if(next == tail_.load(std::memory_order_acquire)) {
21 return false;
22 }
23
24 data_[head] = value;
25 head_.store(next, std::memory_order_release);
26 return true;
27 }
28
29 bool pop(T &value)
30 {
31 const std::size_t tail = tail_.load(std::memory_order_relaxed);
32 if(tail == head_.load(std::memory_order_acquire)) {
33 return false;
34 }
35
36 value = data_[tail];
37 tail_.store(increment(tail), std::memory_order_release);
38 return true;
39 }
40
41 bool empty() const
42 {
43 return head_.load(std::memory_order_acquire) == tail_.load(std::memory_order_acquire);
44 }
45
46 bool full() const
47 {
48 const std::size_t next = increment(head_.load(std::memory_order_acquire));
49 return next == tail_.load(std::memory_order_acquire);
50 }
51
52 constexpr std::size_t capacity() const
53 {
54 return Capacity;
55 }
56
57private:
58 static constexpr std::size_t StorageSize = Capacity + 1;
59
60 // Producer-written head and consumer-written tail each get a full cache
61 // line so cross-core traffic stays on the payload, not on false sharing
62 // between the two indices (same line size the IPC TransportHeader uses).
63 static constexpr std::size_t CacheLineSize = 64;
64
65 static constexpr std::size_t increment(std::size_t value)
66 {
67 return (value + 1) % StorageSize;
68 }
69
70 std::array<T, StorageSize> data_{};
71 alignas(CacheLineSize) std::atomic<std::size_t> head_{0};
72 alignas(CacheLineSize) std::atomic<std::size_t> tail_{0};
73};
74
75} // namespace plcopen::core::rt
constexpr std::size_t capacity() const