我想使用boost::atomic
此处描述的无等待环形缓冲区:
Myproducer
同时提供大量数据(无符号字符,+- 3000 个值),就像它会逐行填充的矩阵一样。push
缓冲区中这些值的最佳方法是什么?我应该只是循环它们还是可以memcpy
以某种方式将它们放在里面?
pop
如果我想同时读取一堆值,也是如此......
这是我想出的,有什么理由不应该是好的?我只需要确定RINGBUFFERSIZE % iSize = 0
。
#define RINGBUFFERSIZE = 30000
ring_[RINGBUFFERSIZE];
bool push(unsigned char* iData, int iSize)
{
size_t head = head_.load(boost::memory_order_relaxed);
size_t next_head = next(head,iSize);
if (next_head == tail_.load(boost::memory_order_acquire))
return false;
memcpy(ring_+head,iData,iSize);
head_.store(next_head, boost::memory_order_release);
}
bool pop(unsigned char * value, int iSize)
{
size_t tail = tail_.load(boost::memory_order_relaxed);
if (tail == head_.load(boost::memory_order_acquire))
return false;
value = &ring_[tail];
tail_.store(next(tail,iSize), boost::memory_order_release);
return true;
}
size_t next(size_t current, int iSize)
{
return (current + iSize) % RINGBUFFERSIZE;
}