1 か月前 · Jul 6, 2026 4:22 AM
For high-frequency IPC between memory reader thread and ImGui render thread:
CPP
template <typename T, size_t Capacity>
class SPSCQueue {
static_assert((Capacity & (Capacity - 1)) == 0, "Capacity must be a power of 2");
T m_buffer[Capacity];
alignas(64) std::atomic<size_t> m_head{0}; // Cache line aligned to prevent false sharing
alignas(64) std::atomic<size_t> m_tail{0};
public:
bool Push(const T& item) {
const size_t tail = m_tail.load(std::memory_order_relaxed);
if ((tail - m_head.load(std::memory_order_acquire)) == Capacity) return false; // Full
m_buffer[tail & (Capacity - 1)] = item;
m_tail.store(tail + 1, std::memory_order_release);
return true;
}
bool Pop(T& item) {
const size_t head = m_head.load(std::memory_order_relaxed);
if (head == m_tail.load(std::memory_order_acquire)) return false; // Empty
item = m_buffer[head & (Capacity - 1)];
m_head.store(head + 1, std::memory_order_release);
return true;
}
};Zero mutex contention, sub-10 nanosecond enqueue latency!