看了咱们官方带的ringbuffer驱动,测试发现每当我放入一个数据时,head加1,而tail不变,是不是这个程序员习惯把tail和head反着用或者还是驱动有问题?
/* * ======== RingBuf_put ======== */ int RingBuf_put(RingBuf_Handle object, unsigned char data) {unsigned int key;unsigned int next;key = HwiP_disable();if (object->count != object->length) {next = (object->head + 1) % object->length;object->buffer[next] = data;object->head = next;object->count++;object->maxCount = (object->count > object->maxCount) ?object->count :object->maxCount;}else {HwiP_restore(key);return (-1);}HwiP_restore(key);return (object->count); }
Felix ZF:
put是对head进行操作,count++
get是对tail进行操作,count–/**======== RingBuf_get ========*/
int RingBuf_get(RingBuf_Handle object, unsigned char *data)
{unsigned int key;
key = HwiP_disable();
if (!object->count) {HwiP_restore(key);return -1;}
*data = object->buffer[object->tail];object->tail = (object->tail + 1) % object->length;object->count–;
HwiP_restore(key);
return (object->count);
}
user4959119:
回复 Felix ZF:
恩这个知道,比如我创建了一个5字节的buffer,为什么我放第6个数据时,head并不移动到开头,只有get后才会移动,这是ringbuffer的原理吗?与我想象的不太一致,我觉得满了后应该自动从开头循环才对。。。
Felix ZF:
回复 user4959119:
创建ringbuf时,给head和tail的初值是不一样的,因此操作上也有点区别。
/*
* ======== RingBuf_construct ========
*/
void RingBuf_construct(RingBuf_Handle object, unsigned char *bufPtr,
size_t bufSize)
{
object->buffer = bufPtr;
object->length = bufSize;
object->count = 0;
object->head = bufSize – 1;
object->tail = 0;
object->maxCount = 0;
}
user4959119:
回复 Felix ZF:
是这样的,另外ringbuffer一般是怎么用?比如我串口一次接收10个字节数据,每中断一次put一个数据,是put一次主循环就get一次还是put10次就get一次全收?
user4959119:
回复 Felix ZF:
你意思是我直接用一个数组来接收数据就行了吗?
user4959119:
回复 Felix ZF:
给力 thank you!