循环队列,支持多线程

 

[cpp] view plaincopy
 
  1. static const char S_FILL[] = "cycle_queue_fill_";  
  2. static const char S_EMPTY[] = "cycle_queue_empty_";  
  3.   
  4. template<class T>  
  5. class CycleQueueT  
  6. {  
  7. private:  
  8.     CycleQueueT(const CycleQueueT&);  
  9.     CycleQueueT& operator= (const CycleQueueT&);  
  10.   
  11. public:  
  12.     CycleQueueT(T *buffer, unsigned int count, const std::string &strConnectName)  
  13.         : count_(count)  
  14.         , front_(0)  
  15.         , rear_(0)  
  16.         , writePtr_(buffer)  
  17.         , readPtr_(buffer)  
  18.         , hFill_(NULL)  
  19.         , hEmpty_(NULL)  
  20.     {  
  21.         hFill_ = CreateSemaphoreA(NULL, count_, count_, (strConnectName+S_FILL).c_str());  
  22.         hEmpty_ = CreateSemaphoreA(NULL, 0, count_, (strConnectName+S_EMPTY).c_str());  
  23.     }  
  24.   
  25.     void set(T *buffer, bool blWrite)  
  26.     {  
  27.         assert(NULL != buffer);  
  28.   
  29.         if (blWrite){  
  30.             writePtr_ = buffer;  
  31.         }  
  32.         else{  
  33.             readPtr_ = buffer;  
  34.         }  
  35.     }  
  36.   
  37.     void put(const T *elem)  
  38.     {  
  39.         WaitForSingleObject(hFill_, INFINITE);  
  40.         memcpy(writePtr_+rear_, elem, sizeof(T));  
  41.         rear_ = (rear_ + 1) % count_;  
  42.         ReleaseSemaphore(hEmpty_, 1, NULL);  
  43.   
  44.     }  
  45.   
  46.     void get(T *elem)  
  47.     {  
  48.         WaitForSingleObject(hEmpty_, INFINITE);  
  49.         memcpy(elem, readPtr_+front_, sizeof(T));  
  50.         front_ = (front_ + 1) % count_;  
  51.         ReleaseSemaphore(hFill_, 1, NULL);  
  52.     }  
  53.   
  54.     unsigned int size() const  
  55.     {  
  56.         return (rear_ - front_ + count_) % count_;  
  57.     }  
  58.   
  59. private:  
  60.     unsigned int count_;  
  61.     unsigned int front_;  
  62.     unsigned int rear_;  
  63.     T *writePtr_;  
  64.     T *readPtr_;  
  65.     void *hFill_;  
  66.     void *hEmpty_;  
  67. };  
原文地址:https://www.cnblogs.com/lvdongjie/p/4461488.html