c++线程池

#include "MemPool.h"


CMemPool::CMemPool(int 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));
}


// CMyMemPool.cpp : 定义控制台应用程序的入口点。
//


//#include "stdafx.h"




#define DATA_BLOCK_LEN 1500


int _tmain(int argc, _TCHAR* argv[])
{
CMemPool myPool1(DATA_BLOCK_LEN, 0, 10);

cout<<"myPool1 block size = "<<myPool1.BlockSize()<<endl;
cout<<"myPool1 allocated block num = "<<myPool1.Allocated()<<endl;
cout<<"myPool1 available block num = "<<myPool1.Available()<<endl<<endl;

std::vector<void*> ptrs;
for (int i = 0; i < 10; ++i)
{
ptrs.push_back(myPool1.Get());
}

myPool1.Get();

int iavilable = 0;
for (std::vector<void*>::iterator it = ptrs.begin(); it != ptrs.end(); ++it)
{
myPool1.Release(*it);
++iavilable;
cout<<"myPool1 available block num = "<<myPool1.Available()<<endl;
}

CMemPool myPool2(DATA_BLOCK_LEN, 5, 10);
cout<<endl<<"myPool2 block size = "<<myPool2.BlockSize()<<endl;
cout<<"myPool2 allocated block num = "<<myPool2.Allocated()<<endl;
cout<<"myPool2 available block num = "<<myPool2.Available()<<endl;

int iWait;
cin>>iWait;

return 0;
}

你可能感兴趣的:(c++线程池)