#ifndef _MEM_POOL_H
#define _MEM_POOL_H
#include <vector>
#include <iostream>
#include "Lock.h"
using namespace std;
class CMemPool
{
public:
//创建大小为blockSize的内存块,内存池数目为预分配的数目preAlloc
CMemPool(std::size_t blockSize, int preAlloc = 0, int maxAlloc = 0);
~CMemPool();
//获取一个内存块。如果内存池中没有足够的内存块,则会自动分配新的内存块
//如果分配的内存块数目达到了最大值,则会返回一个异常
void* Get();
//释放当前内存块,将其插入内存池
void Release(void* ptr);
//返回内存块大小
std::size_t BlockSize() const;
//返回内存池中内存块数目
int Allocated() const;
//返回内存池中可用的内存块数目
int Available() const;
private:
CMemPool();
CMemPool(const CMemPool&);
CMemPool& operator = (const CMemPool&);
enum
{
BLOCK_RESERVE = 32
};
typedef std::vector<char*> BlockVec;
std::size_t m_blockSize;
int m_maxAlloc;
int m_allocated;
BlockVec m_blocks;
CMutex m_mutex;
};
inline std::size_t CMemPool::BlockSize() const
{
return m_blockSize;
}
inline int CMemPool::Allocated() const
{
return m_allocated;
}
inline int CMemPool::Available() const
{
return (int) m_blocks.size();
}
#endif
#include "MemPool.h"
CMemPool::CMemPool(std::size_t blockSize, int preAlloc, int maxAlloc):
m_blockSize(blockSize),
m_maxAlloc(maxAlloc),
m_allocated(preAlloc)
{
if ( preAlloc < 0 || maxAlloc == 0 || maxAlloc < preAlloc )
{
cout<<"CMemPool::CMemPool parameter error."<<endl;
}
int r = BLOCK_RESERVE;
if (preAlloc > r)
r = preAlloc;
if (maxAlloc > 0 && maxAlloc < r)
r = maxAlloc;
m_blocks.reserve(r);
for (int i = 0; i < preAlloc; ++i)
{
m_blocks.push_back(new char[m_blockSize]);
}
}
CMemPool::~CMemPool()
{
for (BlockVec::iterator it = m_blocks.begin(); it != m_blocks.end(); ++it)
{
delete [] *it;
}
}
void* CMemPool::Get()
{
CLock lock(m_mutex);
if (m_blocks.empty())
{
if (m_maxAlloc == 0 || m_allocated < m_maxAlloc)
{
++m_allocated;
return new char[m_blockSize];
}
else
{
cout<<"CMemPool::get CMemPool exhausted."<<endl;
return (void *)NULL;
}
}
else
{
char* ptr = m_blocks.back();
m_blocks.pop_back();
return ptr;
}
}
void CMemPool::Release(void* ptr)
{
CLock lock(m_mutex);
m_blocks.push_back(reinterpret_cast<char*>(ptr));
}