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;
}

posted @ 2018-05-15 23:08  caopf  阅读(178)  评论(1编辑  收藏  举报