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. };  
  • 相关阅读:
    原码、反码、补码,计算机中负数的表示
    [转]Vue 2.0——渐进式前端解决方案
    关于MySQL的tinyint(3)问题
    js对象的深拷贝及其的几种方法
    深入 js 深拷贝对象
    JS 数组克隆方法总结
    Undefined class constant 'MYSQL_ATTR_INIT_COMMAND'
    邮件措辞小计
    Forbidden You don't have permission to access / on this server PHP
    正则表达式
  • 原文地址:https://www.cnblogs.com/lvdongjie/p/4461488.html
Copyright © 2011-2022 走看看