我刚接受采访并要求用旋转实现一个环形缓冲区..所以我想出了这个(我只假设一个生产者和一个消费者= p)...我很好奇看到什么样的你们看到的错误,任何评论......尤其是这一行:
if ((m_tail + 1) % m_size == m_head){
这是线程安全的吗?我是否需要临时原子int来保存计算?
class RingBufferSpin {
private:
std::atomic<bool> m_ready;
std::atomic<int> m_head;
std::atomic<int> m_tail;
int *m_data;
int m_size;
public:
RingBufferSpin(int size){
m_data = new int[size];
m_size = size;
m_head = 0;
m_tail = 0;
}
void Enqueue(int o){
if ((m_tail + 1) % m_size == m_head){
m_ready.store(false, memory_order_release);
int *m_newdata = new int[m_size * 2];
if (m_head > m_tail){
memcpy(m_new_data, m_data, m_head);
} else if (m_tail < m_head){
memcpy(m_new_data, m_data, m_head);
memcpy(m_new_data[(m_head + m_size)], m_data[m_tail], m_size - m_tail);
}
delete[] m_data;
m_data = m_newdata;
m_ready.store(true, memory_order_release);
}
m_data[m_head] = o;
m_head.store((m_head + 1) % m_size);
}
int Dequeue(){
while(!m_ready.load(memory_order_acquire)){
// __asm__ pause
}
int t = m_data[m_tail];
m_tail.store(m_tail + 1 % m_size);
return t;
}
~RingBufferSpin(){
delete[] m_data;
}
}
非常感谢!