#ifndef _MEM_POOL_H
#define _MEM_POOL_H
#include <vector>
#include <iostream>
#include "Lock.h"
using namespace std;
class CMemPool
{
public:
//創(chuàng)建大小為blockSize的內(nèi)存塊顾瞪,內(nèi)存池?cái)?shù)目為預(yù)分配的數(shù)目preAlloc
CMemPool(std::size_t blockSize, int preAlloc = 0, int maxAlloc = 0);
~CMemPool();
//獲取一個(gè)內(nèi)存塊鳖轰。如果內(nèi)存池中沒(méi)有足夠的內(nèi)存塊疙咸,則會(huì)自動(dòng)分配新的內(nèi)存塊
//如果分配的內(nèi)存塊數(shù)目達(dá)到了最大值,則會(huì)返回一個(gè)異常
void* Get();
//釋放當(dāng)前內(nèi)存塊,將其插入內(nèi)存池
void Release(void* ptr);
//返回內(nèi)存塊大小
std::size_t BlockSize() const;
//返回內(nèi)存池中內(nèi)存塊數(shù)目
int Allocated() const;
//返回內(nèi)存池中可用的內(nèi)存塊數(shù)目
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));
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者