读书人

环形缓冲区的一个有关问题

发布时间: 2012-04-19 14:36:43 作者: rapoo

环形缓冲区的一个问题

C/C++ code
/*  * __kfifo_put - puts some data into the FIFO, no locking version  * Note that with only one concurrent reader and one concurrent  * writer, you don't need extra locking to use these functions.  */  unsigned int __kfifo_put(struct kfifo *fifo,        unsigned char *buffer, unsigned int len)  {   unsigned int l;   len = min(len, fifo->size - fifo->in + fifo->out);   /* first put the data starting from fifo->in to buffer end */   l = min(len, fifo->size - (fifo->in & (fifo->size - 1)));   memcpy(fifo->buffer + (fifo->in & (fifo->size - 1)), buffer, l);   /* then put the rest (if any) at the beginning of the buffer */   memcpy(fifo->buffer, buffer + l, len - l);   fifo->in += len;   return len;  }  /*  * __kfifo_get - gets some data from the FIFO, no locking version  * Note that with only one concurrent reader and one concurrent  * writer, you don't need extra locking to use these functions.  */  unsigned int __kfifo_get(struct kfifo *fifo,      unsigned char *buffer, unsigned int len)  {   unsigned int l;   len = min(len, fifo->in - fifo->out);   /* first get the data from fifo->out until the end of the buffer */   l = min(len, fifo->size - (fifo->out & (fifo->size - 1)));   memcpy(buffer, fifo->buffer + (fifo->out & (fifo->size - 1)), l);   /* then get the rest (if any) from the beginning of the buffer */   memcpy(buffer + l, fifo->buffer, len - l);   fifo->out += len;   return len;  } 

放入数据,假设整个buffer=9(下标0—8),in指针指在2这里,按照代码,memcpy(fifo->buffer + (fifo->in & (fifo->size - 1)), buffer, l); 这样本来是从2写到8,假设是“abcdefg”,但是fifo->in & (fifo->size - 1)), 2&8=0,buffer只能从0放到底,这不是不对了??这个& (fifo->size - 1)), 的意思是不能超过这个下标,但是也有可能把本来下标给清0啊,求教

[解决办法]
fifo->in & (fifo->size - 1))
就是 为fifo->in 转化为 buffer的小标吧

他这么写的前提是fifo->size是 2^n吧
只有这样才可以满足要求

如果是对任意大小的size fifo->in % (fifo->size)) 也行吧

读书人网 >C++

热点推荐