为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 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |
你可能对下面的文章感兴趣
上一篇: 如何成为一名C++程序员下一篇: C++箴言:理解inline化的介入和排除
关于为C++标准库容器写自己的内存分配程序的所有评论