環形緩衝區C語言實現

2021-08-25 14:27:18 字數 3200 閱讀 2257

環形緩衝區的特性

1、先進新出

2、當緩衝區被使用完,且又有新的資料需要儲存時,丟掉歷史最久的資料,儲存最新資料

現實中的儲存介質都是線性的,因此我們需要做一下處理,才能在功能上實現環形緩衝區

演算法說明:

1、phead和ptail分別是連續儲存介質的首位址和尾位址

2、ptail - phead 的值是環形緩衝區的總長度

3、pvalid 是使用區域的起始指標,取資料時的起點,當取資料時pvalid要發生偏移

4、pvalidtail 是使用區域的的結尾指標,存資料時的起點,當存資料時,pvalidtail要發生偏移

5、現有長度為addlen位元組要存入,當pvalidtail + addlen > ptail 時(超出了緩衝區,這時就要繞到開頭phead)

int len1 = ptail - pvalidtail;

int len2 = addlen - len1;

pvalidtail = phead + len2;//新的使用區的尾指標

6、判斷總長度是否變更,即是否有資料覆蓋pvalid所指向的區域,如果有,要偏移pvalid

#include #include #include #include #include "ringbuffer.h"

#define buffer_size 16 //緩衝區的長度,可以修改

static u32 validlen;//已使用的資料長度

static u8* phead = null;//環形儲存區的首位址

static u8* ptail = null;//環形儲存區的結尾位址

static u8* pvalid = null;//已使用的緩衝區的首位址

static u8* pvalidtail = null;//已使用的緩衝區的尾位址

/* * 初始化環形緩衝區

* 環形緩衝區這裡可以是malloc申請的記憶體,也可以是flash儲存介質

* */

void initringbuffer(void)

pvalid = pvalidtail = phead;

ptail = phead + buffer_size;

validlen = 0;}/*

* function:向緩衝區中寫入資料

* param:@buffer 寫入的資料指標

* @addlen 寫入的資料長度

* return:-1:寫入長度過大

* -2:緩衝區沒有初始化

* */

int wirteringbuffer(u8* buffer,u32 addlen)

else

//需重新計算已使用區的起始位置

if(validlen + addlen > buffer_size)

else

validlen = buffer_size;

}else

return 0;}/*

* function:從緩衝區內取出資料

* param :@buffer:接受讀取資料的buffer

* @len:將要讀取的資料的長度

* return :-1:沒有初始化

* >0:實際讀取的長度

* */

int readringbuffer(u8* buffer,u32 len)

else

validlen -= len;//更新已使用緩衝區的長度

return len;}/*

* function:獲取已使用緩衝區的長度

* return :已使用的buffer長度

* */

u32 getringbuffervalidlen(void)

/* * function:釋放環形緩衝區

* */

void releaseringbuffer(void)

ringbuffer.h

#ifndef ringbuffer_h_

#define ringbuffer_h_

typedef unsigned char u8;

typedef unsigned int u32;

void initringbuffer(void);

int wirteringbuffer(u8* buffer,u32 len);

int readringbuffer(u8* buffer,u32 len);

u32 getringbuffervalidlen(void);

void releaseringbuffer(void);

#endif /* ringbuffer_h_ */

測試 main 函式

#include #include #include "ringbuffer.h"

// 主函式

int main()

{ char c;

int readlen;

u8 readbuffer[10];

//setvbuf(stdout,null,_ionbf,0); //pinrtf、putchar不能立馬輸出,開啟此注釋

initringbuffer();

printf("please enter a line [blank line to terminate]> ");

do{c=getchar();

putchar(c);

switch(c)

{ case 'q':

goto exit;

break;

case 'r':

readlen = readringbuffer(readbuffer,10);

printf("readringbuffer len:%d\n",readlen);

if(readlen > 0){

printf("readringbuffer:");

for(int i=0;i微控制器開發

環形緩衝區C語言實現

typedef unsigned char u8 typedef unsigned int u32 define buffer size 1024 500 緩衝區的長度,可以修改 static u32 validlen 已使用的資料長度 static u8 phead null 環形儲存區的首位址 ...

環形緩衝區的C語言實現

include include include include include define buffsize 1024 1024 define min x,y x y x y pthread mutex t lock pthread mutex initializer struct cycle b...

C 語言中實現環形緩衝區

1.實現 include include include include include define buffsize 1024 1024 define min x,y x y x y pthread mutex t lock pthread mutex initializer struct cy...