解决使用pthread_create函数造成的内存泄露

首先来看一段程序:

  1. //test1.cc  
  2. #include <iostream>  
  3. #include <pthread.h>  
  4. #include <unistd.h>  
  5. #include <stdio.h>  
  6. using namespace std;  
  7. const int MAX_THREADS = 10000;  
  8.   
  9. void* thread1(void *param)  
  10. {  
  11.     char buff[1024] = {'\0'};  
  12.     cout << "I am ok" << buff << endl;  
  13. }  
  14.   
  15. int main()  
  16. {  
  17.     pthread_t pid[MAX_THREADS];  
  18.     for(int i = 0; i < MAX_THREADS; i++)  
  19.     {  
  20.     pthread_create(&pid[i], NULL, thread1, NULL);  
  21.     sleep(1);  
  22.     }  
  23.   
  24.     return 0;  
  25. }  

程序刚开始运行时内存截图:


程序运行一段时间后内存截图:


从上面两个截图中比较会发现,程序test1使用的内存越来越多,到底是什么原因造成的内存泄露呢?

因为在默认情况下通过pthread_create函数创建的线程是非分离属性的,由pthread_create函数的第二个参数决定,在非分离的情况下,当一个线程结束的时候,它所占用的系统资源并没有完全真正的释放,也没有真正终止。只有当pthread_join函数返回时,该线程才会释放自己的资源。而在分离属性的情况下,一个线程结束会立即释放它所占用的资源。


下面给出两种方法解决pthread_create造成的内存泄露

方法1:

  1. //test2.cc  
  2. #include <iostream>  
  3. #include <pthread.h>  
  4. #include <unistd.h>  
  5. #include <iostream>  
  6. using namespace std;  
  7. const int MAX_THREADS = 10000;  
  8.   
  9. void* thread1(void *param)  
  10. {  
  11.     char buff[1024] = {'\0'};  
  12.     cout << "I am ok" << buff << endl;  
  13. }  
  14.   
  15. int main()  
  16. {  
  17.     pthread_t pid[MAX_THREADS];  
  18.     for(int i = 0; i < MAX_THREADS; i++)  
  19.     {  
  20.     //设置线程分离属性  
  21.     pthread_attr_t attr;  
  22.     pthread_attr_init(&attr);  
  23.     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);  
  24.     pthread_create(&pid[i], &attr, thread1, NULL);  
  25.     sleep(1);  
  26.     }  
  27.   
  28.     return 0;  
  29. }  

程序刚开始运行时内存截图:


程序运行一段时间后内存截图:



方法2:

  1. //test3.cc  
  2. #include <iostream>  
  3. #include <pthread.h>  
  4. #include <unistd.h>  
  5. #include <stdio.h>  
  6. using namespace std;  
  7. const int MAX_THREADS = 10000;  
  8.   
  9. void* thread1(void *param)  
  10. {  
  11.     char buff[1024] = {'\0'};  
  12.     cout << "I am ok" << buff << endl;  
  13.     pthread_detach(pthread_self());  
  14. }  
  15.   
  16. int main()  
  17. {  
  18.     pthread_t pid[MAX_THREADS];  
  19.     for(int i = 0; i < MAX_THREADS; i++)  
  20.     {  
  21.     pthread_create(&pid[i], NULL, thread1, NULL);  
  22.     sleep(1);  
  23.     }  
  24.   
  25.     return 0;  
  26. }  

程序刚开始运行时内存截图:


程序运行一段时间后内存截图:



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值