ring_buffer

Posted caopf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ring_buffer相关的知识,希望对你有一定的参考价值。

writepos+1 != readpos,也就是writepos+1 赶上readpos,也就是没有空间可写了
readpos != writepos 也就是readpos没赶上writepos,也就可读了

 

template <class T>
class ring_buffer {
public:
ring_buffer(int ring_size) : read_pos(0), write_pos(0) {
this->ring_size = ring_size;
this->ring_mem = new T*[ring_size];
memset(this->ring_mem, 0, ring_size * sizeof(NULL));
pthread_spin_init (&spinlock, 0);
}

~ring_buffer() {
delete[] ring_mem;
}

/*
* 环形内存写操作,写入成功返回true,否则返回false
*/
bool write(T *t) {
//自旋锁--加锁
pthread_spin_lock (&spinlock);
bool ret = false;
int wp = (write_pos + 1) & ring_size;
if(read_pos ^ wp) {
ring_mem[write_pos] = t;
write_pos = wp;
ret = true;
}
//自旋锁--解锁
pthread_spin_unlock(&spinlock);
return ret;
}

/*
* 环形内存读操作,读取成功返回true,否则返回false
*/
bool read(T **t) {
int ret = false;
if(read_pos ^ write_pos) {
*t = ring_mem[read_pos];
read_pos = (read_pos + 1) & ring_size;
ret = true;
}
return ret;
}

以上是关于ring_buffer的主要内容,如果未能解决你的问题,请参考以下文章