注册 登录
自由的生活_软路由 返回首页

心想事成的个人空间 https://bbs.routerclub.com/?681 [收藏] [复制] [分享] [RSS]

日志

从nginx中提取出来的内存池代码

已有 1294 次阅读2013-2-20 13:27

代码很简单,但是没有线程锁定。

最近学习nginx的源代码,深深地喜欢它的内存池管理方式,一次性申请大块的内存以供分配,避免了小内存的频繁申请释放产生的碎片,而且统一的内存释放可以保证不会有内存泄露。

 

我在此把nginx的内存池管理代码提取出来方便单独使用。(代码下载地址 http://dl.dbank.com/c0p7h49ts8

使用方法如下:

  1. #include<iostream>  
  2. #include"mem_pool.h"//需要包含此头文件  
  3.   
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     mem_pool *pool = mem_create_pool(1024);//创建一个1024字节大小的内存池(不用担心不够用,nginx遇到内存不足时会自己申请足够的内存)  
  9.   
  10.     char *mychar = (char *)mem_palloc(pool,100);//请求1:100字节的内存  
  11.     strcpy(mychar,"use mem_pool to manage your memory 100");  
  12.     cout << mychar << endl;  
  13.   
  14.     mychar = (char *)mem_palloc(pool,300);//请求2:300字节的内存  
  15.     strcpy(mychar,"use mem_pool to manage your memory 300");  
  16.     cout << mychar << endl;  
  17.   
  18.     mychar = (char *)mem_palloc(pool,1000);//请求3:1000字节的内存  
  19.     strcpy(mychar,"use mem_pool to manage your memory 1000");  
  20.     cout << mychar << endl;  
  21.   
  22.     int *arr = (int *)mem_palloc(pool,sizeof(int)*4);//请求4:一个整型数组,数组大小自定义为4  
  23.     arr[0]=3;  
  24.     arr[1]=4;  
  25.     arr[2]=5;  
  26.     arr[3]=6;  
  27.   
  28.     printf("%d %d %d %d",arr[0],arr[1],arr[2],arr[3]);  
  29.     mem_destroy_pool(pool);//统一销毁内存池,不会有内存泄露  
  30.   
  31.     return 0;  
  32. }  


上面我们一共有4次内存申请,由于使用了nginx的内存池,我们通过valgrind一款用于内存调试、内存泄漏检测以及性能分析的软件开发工具)运行程序测试内存分配回收情况

  1. vm6245:/var/samba/mem_pool # g++ test.cpp mem_pool.cpp  
  2. vm6245:/var/samba/mem_pool # valgrind ./a.out  
  3. ==25677== Memcheck, a memory error detector  
  4. ==25677== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.  
  5. ==25677== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info  
  6. ==25677== Command: ./a.out  
  7. ==25677==  
  8. use mem_pool to manage your memory 100  
  9. use mem_pool to manage your memory 300  
  10. use mem_pool to manage your memory 1000  
  11. 3 4 5 6==25677==  
  12. ==25677== HEAP SUMMARY:  
  13. ==25677==     in use at exit: 0 bytes in 0 blocks  
  14. ==25677==   total heap usage: 2 allocs, 2 frees, 2,024 bytes allocated  
  15. ==25677==  
  16. ==25677== All heap blocks were freed -- no leaks are possible  
  17. ==25677==  
  18. ==25677== For counts of detected and suppressed errors, rerun with: -v  
  19. ==25677== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)  

我们可以看到nginx内存池只进行了两次内存申请,并且都得到了释放,没有内存泄露。我们平时做C/C++程序开发最头疼的应该就是内存泄露的问题了吧,多学习一些优秀的开源软件对于内存的管理方式,受益匪浅。

路过

雷人

握手

鲜花

鸡蛋

评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 注册

QQ|Archiver|手机版|小黑屋|软路由 ( 渝ICP备15001194号-1|渝公网安备 50011602500124号 )

GMT+8, 2024-5-10 15:31 , Processed in 0.060857 second(s), 5 queries , Gzip On, Redis On.

Powered by Discuz! X3.5 Licensed

© 2001-2023 Discuz! Team.

返回顶部