首页 > 其他 > 详细

ring_buffer

时间:2018-05-15 23:39:27      阅读:195      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/caopf/p/9043648.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!