C 環形緩衝區的簡單實現

2021-10-04 17:33:32 字數 1110 閱讀 2429

分享乙個在工作中用到的簡單的環形緩衝區。構造簡單,可以改造到qt中使用,也可以直接在vs下使用。

所謂環形緩衝區,其實就是帶有標識緩衝區中資料頭、尾位置的緩衝區,這個緩衝區根據業務的不同,要設定的稍微大一點,不能一有資料過來就填滿了,這樣就失去使用的意義了。

在實際工作中,我們使用tcp和裝置進行通訊,如果資料流量過大,可以先把資料接收到資料緩衝區中,處理之後再取出。我們定義的包協議可以採用定長包,可以採用不定長度的包,環形緩衝區都能處理。

//標頭檔案定義

class circlebuffer

;

//原始檔實現

circlebuffer::circlebuffer()

circlebuffer::~circlebuffer()

}int circlebuffer::getdatalength()

else //多次訪問之後尾部索引有可能比頭部索引要小

}qint16 circlebuffer::getfreebufferlength()

bool circlebuffer::empty()

void circlebuffer::copydata(char *data, int len)

else

else

break; //不處理}}

else

}}//提供給使用者的介面

//重置緩衝區

void circlebuffer::resetbuffer()

//處理資料

void circlebuffer::pushdata(char *data, int len)

else

//更新各種資料

head = 0;

rear = data_len;

maxbuf = maxbuf +len;

delete buf;

buf = p;

//拷貝資料

copydata(data,len);

}//2, 最後再處理資料

processdata();

}

環形緩衝區的c實現

標頭檔案 ifndef xbuf h define xbuf h define xbufdefaultsize 1024 1024 緩衝區預設大小 typedef unsigned int uint32 建立乙個環形緩衝區 size為緩衝區大小 void x buf create uint32 si...

c 環形緩衝區

public class circularbuffer icollection,ienumerable,icollection,ienumerable public circularbuffer int capacity,bool allowoverflow public bool allowove...

環形緩衝區的實現

乙個簡單的環形緩衝區,沒有寫加解鎖的部分,用於多執行緒的話還是自己加吧.pragma once include stdio.h include stdlib.h include memory.h namespace linker ring bool put elementtype e else bo...