環形緩衝區 環形緩衝佇列學習

2021-06-27 04:36:43 字數 1340 閱讀 2981

專案中需要執行緒之間共享乙個緩衝fifo佇列,乙個執行緒往佇列中添資料,另乙個執行緒取資料(經典的生產者-消費者問題)。開始考慮用stl的vector容器, 但不需要隨機訪問,頻繁的刪除最前的元素引起記憶體移動,降低了效率。使用linklist做佇列的話,也需要頻繁分配和釋放結點記憶體。於是自己實現乙個有限大小的fifo佇列,直接採用陣列進行環形讀取。

佇列的讀寫需要在外部程序執行緒同步(另外寫了乙個rwguard類, 見另一文)

到專案的針對性簡單性,實現了乙個簡單的環形緩衝佇列,比stl的vector簡單

ps: 第一次使用模板,原來類模板的定義要放在.h 檔案中, 不然會出現連線錯誤。

template

class csharequeue 

//返回當前個數

unsigned int size()

//是否滿//warning: 需要外部控制資料一致性

bool isfull()

bool isempty()

protected:

uint m_head;

uint m_tail;

uint m_size;

uint m_capacity;

_type *pbuf;

};template

csharequeue<_type>::csharequeue() : m_head(0), m_tail(0), m_size(0)

template

csharequeue<_type>::csharequeue(unsigned int bufsize) : m_head(0), m_tail(0)

else

}template

csharequeue<_type>::~csharequeue()

//前面彈出乙個元素

template

_type csharequeue<_type>::pop_front()

_type itemtmp;

itemtmp = pbuf[m_head];

m_head = (m_head + 1) % m_capacity;

--m_size;

return itemtmp;

}//從尾部加入佇列

template

bool csharequeue<_type>::push_back( _type item)

pbuf[m_tail] = item;

m_tail = (m_tail + 1) % m_capacity;

++m_size;

return true;

}#endif // !defined(_daly_csharequeue_h_)

環形緩衝區

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...

環形緩衝區

define print buf size 16 1024 static char g pcnetprintbuf 環形緩衝區的首位址 static int g ireadpos 0 環形緩衝區讀的位置 static int g iwritepos 0 環形緩衝區寫的位置 intinit 判斷環形緩...

環形緩衝區

環形緩衝區要維護兩個索引,分別對應寫入端 w 和讀取端 r 寫入 push 的時候,先確保環沒滿,然後把資料複製到 w 所對應的元素,最後 w 指向下乙個元素 讀取 pop 的時候,先確保環沒空,然後返回 r 對應的元素,最後 r 指向下乙個元素。上述的操作並不複雜,不過有乙個小小的麻煩 空環和滿環...