zoukankan      html  css  js  c++  java
  • 循环队列,支持多线程

     

    [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. };  
  • 相关阅读:
    (转)Linux系统调用和库函数调用的区别
    一个“梦想实践重度障碍者”的思考
    按字节输出数据
    内存区划分、内存分配、常量存储区、堆、栈、自由存储区、全局区[C++][内存管理]
    VimdiffVIM的比较和合并工具
    [每天进步一点 流水账]回顾总结
    计算机就业方向
    ofstream和ifstream详细用法(转)
    ECMAScript 运算符关系运算符
    ECMAScript 语句标签语句
  • 原文地址:https://www.cnblogs.com/lvdongjie/p/4461488.html
Copyright © 2011-2022 走看看