首页 > 代码库 > 无锁内存缓冲池

无锁内存缓冲池

/*
                无锁内存缓冲池
其特点如下:
池内存的申请和释放不会使用锁,只会用到微耗的interlockedincrement和interlockeddecrement函数
池内存总大小和池内内存块的大小是固定长度的,通过构造函数的参数指定;
分配出来的池内存是经过memset确认的物理内存;
池大小是固定的,若池中空闲内存不足以提供所需,则池内存分配函数利用malloc向系统额外申请,但新申请的内存不并入池中;
通过GetBuf()和FreeBuf两个函数进程池内存的申请和释放;
*/
#ifndef HBUFFER_HPP
#define HBUFFER_HPP

inline void IncPtr(void **p,int i)
{  
    *p = (void*)((int)*p + i);
}

class HBuff
{
public:
    HBuff(long buf_count,long buf_size)
        :m_buf_count(buf_count),m_buf_size(buf_size)
    {
        m_buf = malloc(buf_count * buf_size);
        memset(m_buf,0,buf_count * buf_size);
        m_buf_end = (unsigned long)m_buf + (buf_count *  buf_size);
        m_buf_free = new void*[buf_count];
        void *p = m_buf;
        for(size_t i=0;i<buf_count;++i)
        {
            m_buf_free[i] = p;
            IncPtr(&p,buf_size);
        }
        m_buf_free_pos = buf_count - 1;       
    }
    ~HBuff()
    {
        ::free(m_buf);
        delete [] m_buf_free;        
    }
    void *GetBuf()
    {
        long i = InterlockedDecrement(&m_buf_free_pos);
        if(i < -1)
        {
            void *ret = malloc(m_buf_size);
            memset(ret,0,m_buf_size);
            return ret;
        }
        else
        {
            return m_buf_free[i+1];
        }
    }
    void FreeBuf(void *buf)
    {
        if((unsigned long)buf >= m_buf_end || (unsigned long)buf < (unsigned long)m_buf)
            ::free(buf);
        else
        {
            long i = InterlockedIncrement(&m_buf_free_pos);
            m_buf_free[i] = buf;            
        }
    }
private:
    HBuff(const HBuff&);
    HBuff& operator=(const HBuff&);
private:
    long    m_buf_count;
    long    m_buf_size;
    unsigned long m_buf_end;
    void*   m_buf;
    void**   m_buf_free;
    long volatile m_buf_free_pos;    
};

#endif

无锁内存缓冲池