快速业务通道

为C++标准库容器写自己的内存分配程序

作者 佚名技术 来源 程序设计 浏览 发布时间 2012-06-30
++)
{
if(pHead->sFreelistIndex[i] == bytes)
break;
}
std::cout<<"freelist_getindex:bytes="<<bytes<<" , return="<<i<<std::endl;
return i;
};
template <class T>
char* MyAlloc<T>::chunk_alloc(int size, int *nobjs)
{
char* result;
int counts = *nobjs;
int total_bytes = size * counts;
int bytes_left = int(pHead->pEndfree - pHead->pStartfree);
std::cout<<"chunk_alloc:total_bytes = "<<total_bytes
<<",bytes_left = "<<bytes_left<<std::endl;
if (bytes_left >= total_bytes)
{
result = pHead->pStartfree;
pHead->pStartfree += total_bytes;
std::cout<<"chunk_alloc:total_bytes = "<<total_bytes
<<",result = "<<*result<<",start_free = "<<&(pHead->pStartfree)<<std::endl;
}
else if (bytes_left >= size)
{
counts = bytes_left/size;
total_bytes = size * counts;
result = pHead->pStartfree;
pHead->pStartfree += total_bytes;
*nobjs = counts;
std::cout<<"chunk_alloc:total_bytes = "<<total_bytes<<",nobjs = "<<nobjs
<<",result = "<<*result<<",start_free = "<<&(pHead->pStartfree)<<std::endl;
}
else
{
/*还需要处理回收其他空闲freelist里面的空间*/
result = NULL;
}
return(result);
};
template <class T>
void* MyAlloc<T>::refill(int num,int n)
{
int counts = num;
int *nobjs = &counts;
char* chunk;
Obj** my_free_list;
Obj* result;
Obj* current_obj;
Obj* next_obj;
int i;
chunk = chunk_alloc(n, nobjs);
if(chunk == NULL)
{
return(chunk);
}
counts = *nobjs;
if (1 == counts)
{
return(chunk);
}
my_free_list = pHead->uFreelist + freelist_index(n);
result = (Obj*)chunk;
*my_free_list = next_obj = (Obj*)(chunk + n*num);
for (i = 1; ; i++)
{
current_obj = next_obj;
next_obj = (Obj*)((char*)next_obj + n);
if (counts - 1 == i)
{
current_obj->M_free_list_link = 0;
break;
}
else
{
current_obj->M_free_list_link = next_obj;
}
}
return(result);
};
/*这个函数可以改写成自己的共享内存分配函数*/
static void InitShm()
{
int i,size=1000;
pHead = (Cookie*)malloc(sizeof(Cookie)+size);
pHead->iTotalsize = sizeof(Cookie)+size;
pHead->pStartall = pHead;
pHead->pStartfree = (char*)pHead + sizeof(Cookie);
pHead->pEndfree = (char*)pHead + pHead->iTotalsize;
for(i=0 ; i <NODENUMS ; i++)
{
pHead->sFreelistIndex[i]=0;
pHead->uFreelist[i]=0;
pHead->iUseNum[i]=0;
}
}
static void PrintFreelistAndCookie()
{
int i,j;
Obj* my_free_list;
std::cout<<"Cookie info :"<<std::endl;
std::cout<<&

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号