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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值