環形緩衝隊列

來源:互聯網
上載者:User

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

    隊列的讀寫需要在外部進程線程同步(另外寫了一個RWGuard類, 見另一文)

到項目的針對性簡單性,實現了一個簡單的環形緩衝隊列,比STL的vector簡單

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

 template <class _Type>
class CShareQueue 
{
public:
 CShareQueue();
 CShareQueue(unsigned int bufsize);
 virtual ~CShareQueue();

 _Type pop_front();
 bool push_back( _Type item);
 //返回容量
 unsigned int capacity() {  //warning:需要外部資料一致性
  return m_capacity;
 }
 //返回當前個數
 unsigned int size() {   //warning:需要外部資料一致性
  return m_size;
 }
 //是否滿   //warning: 需要外部控制資料一致性
 bool IsFull() {
  return (m_size >= m_capacity);
 }

 bool IsEmpty() {
  return (m_size == 0);
 }

protected:
 UINT m_head;
 UINT m_tail;
 UINT m_size;
 UINT m_capacity;
 _Type *pBuf;

};

template <class _Type>
CShareQueue<_Type>::CShareQueue() : m_head(0), m_tail(0), m_size(0)
{
 pBuf = new _Type[512]; //預設512
 m_capacity = 512;
}

template <class _Type>
CShareQueue<_Type>::CShareQueue(unsigned int bufsize) : m_head(0), m_tail(0)
{
 if( bufsize > 512 || bufsize < 1)
 {
  pBuf = new _Type[512];
  m_capacity = 512;
 }
 else
 {
  pBuf = new _Type[bufsize];
  m_capacity = bufsize;
 }
}

template <class _Type>
CShareQueue<_Type>::~CShareQueue()
{
 delete[] pBuf;
 pBuf = NULL;
 m_head = m_tail = m_size = m_capacity = 0;
}

//前面彈出一個元素
template <class _Type>
_Type CShareQueue<_Type>::pop_front()
{
 if( IsEmpty() )
 {
  return NULL;
 }
 _Type itemtmp;
 itemtmp = pBuf[m_head];
 m_head = (m_head + 1) % m_capacity;
 --m_size;
 return itemtmp;

}

//從尾部排入佇列
template <class _Type>
bool CShareQueue<_Type>::push_back( _Type item)
{
 if ( IsFull() )
 {
  return FALSE;
 }
 pBuf[m_tail] = item;
 m_tail = (m_tail + 1) % m_capacity;
 ++m_size;
 return TRUE;
}

#endif // !defined(_DALY_CSHAREQUEUE_H_)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.