这里分享一个自己用纯c实现的环形缓冲区。
环形缓冲区有很多作用,比如嵌入式中的通信可以用环形缓冲区作为信道,一个线程往里放字节,一个线程取字节进行处理,只要保证取的速度大于读的速度,就可以保证通信顺畅进行,不丢一个字节。
简要介绍:
环形缓冲区其实就是一个队列,里头的元素是先入先出的,但是因为其(逻辑上)是环形的,所以不需要像很多队列的实现那样在内部元素变动的时候需要移动内部剩下的元素。这样就使元素出队入队的时间复杂度只有o(1)。具体实现一般有链表和数组两种方法,当不能确定需要的缓冲区大小时使用链表较好,能确定时使用数组可以节省很多动态分配内存的开销。
在嵌入式开发中,一般不动态分配内存,而是使用静态分配的数组。所以这里我使用数组实现了环形缓冲区,为了能够在不同的程序中复用代码,使用结构体模拟了面向对象编程,这样就可以用一套代码管理不同的缓冲区了。
废话不多说,直接上代码。以下是.h 文件:
/************************************************************************************************************* ringqueuestruct* 环形队列结构** file : ringqueue.h* by : lin shijun(http://blog.csdn.net/lin_strong)* date : 2018/02/23* version: v1.2* note(s): 这段程序用来对一个给定的缓冲区进行模拟环形队列的管理* 程序本身不会自动分配缓冲区空间,用户需要自己负责分配空间,并且要保证不直接访问缓存区* // 在某处分配内存空间* rqtype buffer[buffer_size];* ring_queue que,*ptr_que;* unsigned char err;* // 初始化* ptr_que = ringqueueinit(&que,buffer,buffer_size,&err);* if(err == rq_err_none ){* // 初始化成功,使用其他函数* }* history : 2017/04/25 the original version of ringqueuestruct.* 2017/10/16 put functions used frequently,ringqueuein and ringqueueout, in non-banked address;* modify single line function ringqueueisempty and ringqueueisfull to marco function;* to get better efficiency.* 2018/02/23 1.add the marco(rq_argument_check_en) to controll argument check so user can save * more code.* 2.add the addressing mode so the buffer can be defined in banked addressing area.**********************************************************************************************************/#ifndef ring_queue_h#define ring_queue_h/********************************************************************************************** miscellaneous*********************************************************************************************/#ifndef false#define false 0#endif#ifndef true#define true 1#endif/*********************************************************************************************************** addressing mode 寻址模式**********************************************************************************************************/// uncomment the corresponding line to select the addressing mode to the buffer of ringqueue module.// if you don't understand. just use the extended addressing mode// 取消对应行的注释以选择环形缓冲区模块访问缓冲区时使用的寻址方式// 如果你不知道这是什么意思的话,那就用扩展寻址就行了,这是默认的方式// extended addressing mode 扩展区寻址(默认)#define rq_addressing_mode// banked ram addressing mode ram分页区寻址//#define rq_addressing_mode __rptr// global addressing mode 全局寻址//#define rq_addressing_mode __far/*********************************************************************************************************** configuration 配置**********************************************************************************************************/#define rq_argument_check_en true // true: arguments will be checked, however,this will // cost a little code volume./*********************************************************************************************************** constants 常量**********************************************************************************************************/#define rq_err_none 0u#define rq_err_pointer_null 1u#define rq_err_size_zero 2u#define rq_err_buffer_full 3u#define rq_err_buffer_empty 4u#define rq_option_when_full_discard_first 0u // discard the first element when ring buffer is full#define rq_option_when_full_dont_in 1u // discard new element when ring buffer is full/*********************************************************************************************************** data type 数据类型**********************************************************************************************************/// define the data type that stores in the ringqueue. 定义存在环形缓冲区内的数据的类型typedef unsigned char rqtype;typedef rqtype *rq_addressing_mode prqtype;typedef struct { unsigned short ringbufctr; /* number of characters in the ring buffer */ unsigned short ringbufsize; /* ring buffer size */ prqtype ringbufinptr; /* pointer to where next character will be inserted */ prqtype ringbufoutptr; /* pointer from where next character will be extracted */ prqtype ringbuf; /* ring buffer array */ prqtype ringbufend; /* point to the end of the buffer */} ring_queue;/*********************************************************************************************************** function prototypes 函数原型**********************************************************************************************************/ring_queue *ringqueueinit(ring_queue *pqueue,prqtype pbuf,unsigned short bufsize,unsigned char *perr);#pragma code_seg __near_seg non_bankedunsigned short ringqueuein(ring_queue *pqueue,rqtype data,unsigned char option,unsigned char *perr);rqtype ringqueueout(ring_queue *pqueue,unsigned char *perr);#pragma code_seg defaultshort ringqueuematch(ring_queue *pqueue,prqtype pbuf,unsigned short len);void ringqueueclear(ring_queue *pqueue);/*********************************************************************************************************** ringqueueisempty()** description : whether the ringqueue is empty. 环形队列是否为空** arguments : pqueue pointer to the ring queue control block; 指向环形队列控制块的指针** return : true the ringqueue is empty.* false the ringqueue is not empty.* note(s) :**********************************************************************************************************/#define ringqueueisempty(pqueue) ((pqueue)->ringbufctr == 0)/*********************************************************************************************************** ringqueueisfull()** description : whether the ringqueue is full. 环形队列是否为空** arguments : pqueue pointer to the ring queue control block; 指向环形队列控制块的指针** return : true the ringqueue is full.* false the ringqueue is not full.* note(s) :**********************************************************************************************************/#define ringqueueisfull(pqueue) ((pqueue)->ringbufctr >= (pqueue)->ringbufsize)#endif
然后下面是.c文件。
/************************************************************************************************************* ringqueuestruct* 环形队列结构** file : ringqueue.c* by : lin shijun(http://blog.csdn.net/lin_strong)* date : 2018/02/23* version: v1.2 * note(s): ** history : 2017/04/25 the original version of ringqueuestruct.* 2017/10/16 put functions used frequently,ringqueuein and ringqueueout, in non-banked address;* modify single line function ringqueueisempty and ringqueueisfull to marco function;* to get better efficiency.* 2018/02/23 1.add the marco(rq_argument_check_en) to controll argument check so user can save * more code.* 2.add the addressing mode so the buffer can be defined in banked addressing area.**********************************************************************************************************//*********************************************************************************************************** includes**********************************************************************************************************/#include ringqueue.h/*********************************************************************************************************** local function declaration**********************************************************************************************************/#if(rq_argument_check_en == true) #define argcheck(cond,err,rval) if(cond) { *perr = (err); return (rval); }#else #define argcheck(cond,err,rval)#endif // of (spi_argument_check_en == true)/*********************************************************************************************************** local function declare**********************************************************************************************************/#pragma code_seg __near_seg non_banked// 内部使用,给定将给定指针在环形缓冲区内向前移动一步(到尾了会移回头)static void _forwardpointer(ring_queue *pqueue,prqtype* ppointer);#pragma code_seg default/*********************************************************************************************************** ringqueueinit()** description : to initialize the ring queue. 初始化环形队列** arguments : pqueue pointer to the ring queue control block; 指向环形队列控制块的指针* pbuf pointer to the buffer(an array); 指向自定义的缓冲区(实际就是个数组)* bufsize the size of the buffer; 缓冲区的大小;* perr a pointer to a variable containing an error message which will be set by this* function to either:** rq_err_none * rq_err_size_zero* rq_err_pointer_null** return : the pointer to the ring queue control block; 返回指向环形队列控制块的指针* 0x00 if any error; 如果出错了则返回null**note(s):**********************************************************************************************************/ring_queue* ringqueueinit(ring_queue *pqueue,prqtype pbuf,unsigned short bufsize,unsigned char *perr){ argcheck(pqueue == 0x00 || pbuf == 0x00,rq_err_pointer_null,0x00); argcheck(bufsize == 0,rq_err_size_zero,0x00); pqueue->ringbufctr = 0; pqueue->ringbuf = pbuf; pqueue->ringbufinptr = pbuf; pqueue->ringbufoutptr = pbuf; pqueue->ringbufsize = bufsize; pqueue->ringbufend = pbuf + bufsize; *perr = rq_err_none; return pqueue;}/*********************************************************************************************************** ringqueuein()** description : enqueue an element. 入队一个元素** arguments : pqueue pointer to the ring queue control block; 指向环形队列控制块的指针* data the data to enqueue; 要入队的数据* option option when queue is full ,you can choose: 当队列满的时候的选项,你可以选择:* rq_option_when_full_discard_first 抛弃队头的元素来填进去新的元素* rq_option_when_full_dont_in 不入队新给的元素* perr a pointer to a variable containing an error message which will be set by this* function to either:** rq_err_none if no err happen* rq_err_pointer_null if pointer is 0x00* rq_err_buffer_full if buffer is full** return : the elements count after enqueue the element* 调用函数后队列中的元素个数*note(s) :**********************************************************************************************************/#pragma code_seg __near_seg non_bankedunsigned short ringqueuein(ring_queue *pqueue,rqtype data,unsigned char option,unsigned char *perr){ argcheck(pqueue == 0x00,rq_err_pointer_null,0x00); if(pqueue->ringbufctr >= pqueue->ringbufsize){ *perr = rq_err_buffer_full; if(option == rq_option_when_full_discard_first){ _forwardpointer(pqueue,&pqueue->ringbufoutptr); /* wrap out pointer */ }else{ // option == rq_option_when_full_dont_in return pqueue->ringbufctr; } }else{ pqueue->ringbufctr++; /* no, increment character count */ *perr = rq_err_none; } *pqueue->ringbufinptr = data; /* put character into buffer */ _forwardpointer(pqueue,&pqueue->ringbufinptr); /* wrap in pointer */ return pqueue->ringbufctr;}/*********************************************************************************************************** ringqueueout()** description : dequeue an element. 出队一个元素** arguments : pqueue pointer to the ring queue control block; 指向环形队列控制块的指针* perr a pointer to a variable containing an error message which will be set by this* function to either:** rq_err_none if no err happen* rq_err_pointer_null if pointer is 0x00* rq_err_buffer_empty if buffer is empty** return : 0 if any error or the data is 0;* others the data * *note(s):**********************************************************************************************************/rqtype ringqueueout(ring_queue *pqueue,unsigned char *perr){ rqtype data; argcheck(pqueue == 0x00,rq_err_pointer_null,0x00); if(pqueue->ringbufctr == 0){ *perr = rq_err_buffer_empty; return 0; } pqueue->ringbufctr--; /* decrement character count */ data = *pqueue->ringbufoutptr; /* get character from buffer */ _forwardpointer(pqueue,&pqueue->ringbufoutptr); /* wrap out pointer */ *perr = rq_err_none; return data;}#pragma code_seg default/*********************************************************************************************************** ringqueuematch()** description : match the given buffer in ringqueue 在环形队列中匹配给定缓冲区** arguments : pqueue pointer to the ring queue control block; 指向环形队列控制块的指针* pbuf pointer to the chars need to match;* len the length of the chars* return : -1 don't match -1 则没有匹配到* >= 0 match >= 0 则匹配到了**note(s):**********************************************************************************************************/short ringqueuematch(ring_queue *pqueue,prqtype pbuf,unsigned short len){ prqtype pposq,pcurq,pcurb,pendb; unsigned short rlen,cnt; if(len > pqueue->ringbufctr) return -1; pposq = pqueue->ringbufoutptr; pendb = pbuf + len; cnt = 0; rlen = pqueue ->ringbufctr; while(rlen-- >= len){ // if remian length of queue bigger than buffer. continue pcurq = pposq; pcurb = pbuf; while(pcurb != pendb && *pcurq == *pcurb) { // compare one by one,until match all(pcurb==pendb) or some one don't match _forwardpointer(pqueue,&pcurq); pcurb++; } if(pcurb == pendb) // if match all return cnt; cnt++; _forwardpointer(pqueue,&pposq); } return -1;}/*********************************************************************************************************** ringqueueclear()** description: clear the ringqueue. 清空环形队列** arguments : pqueue pointer to the ring queue control block; 指向环形队列控制块的指针** return: ** note(s):**********************************************************************************************************/void ringqueueclear(ring_queue *pqueue){#if(rq_argument_check_en == true) if(pqueue == 0x00) return;#endif pqueue->ringbufctr = 0; pqueue->ringbufinptr = pqueue -> ringbufoutptr;}/*********************************************************************************************************** local function **********************************************************************************************************/#pragma code_seg __near_seg non_bankedstatic void _forwardpointer(ring_queue *pqueue,prqtype* ppointer){ if (++*ppointer == pqueue->ringbufend) *ppointer = pqueue->ringbuf; /* wrap out pointer */ }#pragma code_seg default
简单解释下。
在.h文件中定义了一个环形缓冲区的控制块,当然也可以当其为一个环形缓冲区对象,用户需要为每个环形缓冲区分配一个控制块和其缓冲区(也就是一个数组)。理想情况下,虽然用户知道控制块的结构,但也不应该直接访问内部字段,而应该通过提供的函数来访问。
队列中默认的元素是无符号字符,如果要改成缓存其他类型的话改下.h文件中的typedef unsigned char rqtype;这行就行了。
使用示例:
#include ringqueue.h#define rx_buf_max_size 200 // 定义缓冲区的最大大小为200static unsigned char rxbuffer[rx_buf_max_size]; // 定义缓冲区static ring_queue rxringq; // 定义环形缓冲区的控制块void main(){ unsigned char err; // 初始化缓冲区 ringqueueinit(&rxringq,rxbuffer,rx_buf_max_size,&err); if(err != rq_err_none){ //初始化缓冲区失败的处理 } ……}
然后调用所有方法都需要传递环形缓冲区控制块的指针。如入队就像:
// 往rxringq缓冲区内入队一个元素c,如果满的话丢弃第一个元素ringqueuein(&rxringq,c,rq_option_when_full_discard_first,&err);
出队就像:
// 从rxringq缓冲区内提取一个字符c = ringqueueout(&rxringq,&err);
其他就不一 一举例了。要特别说明下的是ringqueuematch()这个方法并不是队列应该有的方法,这是为了比如我需要在缓冲区中匹配到某一串字符后做某些事情而特别加上的,不需要的话删掉即可。比如我需要一旦出现“abc”就做某些事情,那我代码可以类似这么写:
static const unsigned char* stringswait = abc;……while(true){ //比如从某处获得了下一个字符c …… // 将字符c入队 ringqueuein(&rxringq,c,rq_option_when_full_discard_first,&err); if(ringqueuematch(&rxringq,stringswait,3) >= 0){ // 如果在缓冲区内找到abc // ringqueueclear(&rxringq); // 可能需要清空缓冲区 // 做想要做的事 …… }}
有什么建议或意见请留言,谢谢!
组织研磨仪的具体操作步骤是怎样的
除工业机器人和纺织机械产业外 史陶比尔还提供先进的连接器解决方案
IGBT激励电路
什么是分层架构的依据与原则?本文告诉你答案!
声波电动牙刷哪个牌子的最好?品牌电动牙刷排行推荐
基于C语言实现环形缓冲区/循环队列
如何采用2MHz单芯片降压-升压DC-DC转换器和LED驱动器消除PCB空间受限的困扰
2大目标10大任务 智造规划引领产业新风尚
Intel公布了2018年第四季度及全年财报
2020年首次在首钢示范区启动使用无人驾驶电动车
英特尔CEO帕特·基辛格:融合五大超级技术力量,与中国共建数字世界
回音壁没有“环绕声效果”音质差?也许你买的是条形音箱
关于射频微机电系统开关的那些事儿
d触发器verilog描述
使用诊断与DFM提高可制造性
基于MPS的交换机电源解决方案
传统天线理论与产业发展的困局
人工智能芯片和普通芯片区别
BVV线的结构_BVV线的规格型号
如何从经济学的角度看区块链