To transfer game state coordinates from a background memory reader thread to an ImGui DirectX render thread with zero lock contention:
template<typename T, size_t Capacity>
class LockFreeSPSCQueue {
static_assert((Capacity & (Capacity - 1)) == 0, "Capacity must be a power of 2");
alignas(64) std::atomic<size_t> m_head{0};
alignas(64) std::atomic<size_t> m_tail{0};
alignas(64) T m_buffer[Capacity];
public:
bool Push(const T& item) {
size_t head = m_head.load(std::memory_order_relaxed);
if (head - m_tail.load(std::memory_order_acquire) == Capacity) return false;
m_buffer[head & (Capacity - 1)] = item;
m_head.store(head + 1, std::memory_order_release);
return true;
}
bool Pop(T& outItem) {
size_t tail = m_tail.load(std::memory_order_relaxed);
if (tail == m_head.load(std::memory_order_acquire)) return false;
outItem = m_buffer[tail & (Capacity - 1)];
m_tail.store(tail + 1, std::memory_order_release);
return true;
}
};alignas(64) completely prevents CPU L1/L2 cache false sharing across CPU cores!