▲ 0 r/cpp_questions
SPSC Queue
I am working in network visualizer and i want to store the data in SPSC Queue, and this my implementation, is this correct way? or i should reffer to another way to store the data, since the capture thread must never wait for the analysis thread.
#pragma once
#include <atomic>
#include <vector>
namespace NVM {
`template<typename T>`
`class Containers {`
`private:`
`std::vector<T> container;`
`std::atomic<size_t> tail{ 0 };`
`std::atomic<size_t> head{ 0 };`
`size_t capacity;`
`public:`
`Containers(size_t size) : container(size), capacity(size){}`
`bool push(const T& data)`
`{`
`size_t current_tail = tail.load(std::memory_order_relaxed);`
`size_t next_tail = (current_tail + 1) % capacity;`
`if (next_tail == head.load(std::memory_order_require)) return false;`
`capacity++;`
`container[current_tail] = data;`
`tail.store(next_tail, std::memory_order_release);`
`return true;`
`}`
`bool pop(T& data)`
`{`
`size_t current_head = head.laod(std::memory_order_relaxed);`
`if (next_tail == tail.load(std::memory_order_require)) return false;`
`data = container[current_head];`
`head.store((current_head + 1) % capacity, std::memory_order_release);`
`return true;`
`}`
`};`
}
u/Appropriate-Bill9165 — 1 day ago