1 #pragma once 2 3 #include <atomic> 4 5 template <typename ValueType> 6 class CLockFreeQueue 7 { 8 public: CLockFreeQueue(unsigned int maxItemCount)9 CLockFreeQueue(unsigned int maxItemCount) 10 : m_prodIndex(0) 11 , m_consIndex(0) 12 , m_itemCount(0) 13 , m_maxItemCount(maxItemCount) 14 { 15 m_items = new ValueType[m_maxItemCount]; 16 } 17 ~CLockFreeQueue()18 virtual ~CLockFreeQueue() 19 { 20 delete [] m_items; 21 } 22 TryPop(ValueType & item)23 bool TryPop(ValueType& item) 24 { 25 if(m_itemCount == 0) 26 { 27 return false; 28 } 29 30 item = m_items[m_consIndex]; 31 32 m_consIndex++; 33 m_consIndex %= m_maxItemCount; 34 35 m_itemCount--; 36 37 return true; 38 } 39 TryPush(const ValueType & item)40 bool TryPush(const ValueType& item) 41 { 42 if(m_itemCount == m_maxItemCount) 43 { 44 return false; 45 } 46 47 m_items[m_prodIndex] = item; 48 49 m_prodIndex++; 50 m_prodIndex %= m_maxItemCount; 51 52 m_itemCount++; 53 54 return true; 55 } 56 57 private: 58 ValueType* m_items; 59 std::atomic<unsigned int> m_itemCount; 60 unsigned int m_maxItemCount; 61 unsigned int m_prodIndex; 62 unsigned int m_consIndex; 63 }; 64