解决使用pthread_create函数造成的内存泄露
来源:互联网 发布:apache maven 3.2.5 编辑:程序博客网 时间:2024/05/25 08:15
首先来看一段程序:
- //test1.cc
- #include <iostream>
- #include <pthread.h>
- #include <unistd.h>
- #include <stdio.h>
- using namespace std;
- const int MAX_THREADS = 10000;
- void* thread1(void *param)
- {
- char buff[1024] = {'\0'};
- cout << "I am ok" << buff << endl;
- }
- int main()
- {
- pthread_t pid[MAX_THREADS];
- for(int i = 0; i < MAX_THREADS; i++)
- {
- pthread_create(&pid[i], NULL, thread1, NULL);
- sleep(1);
- }
- return 0;
- }
程序刚开始运行时内存截图:
程序运行一段时间后内存截图:
从上面两个截图中比较会发现,程序test1使用的内存越来越多,到底是什么原因造成的内存泄露呢?
因为在默认情况下通过pthread_create函数创建的线程是非分离属性的,由pthread_create函数的第二个参数决定,在非分离的情况下,当一个线程结束的时候,它所占用的系统资源并没有完全真正的释放,也没有真正终止。只有当pthread_join函数返回时,该线程才会释放自己的资源。而在分离属性的情况下,一个线程结束会立即释放它所占用的资源。
下面给出两种方法解决pthread_create造成的内存泄露
方法1:
- //test2.cc
- #include <iostream>
- #include <pthread.h>
- #include <unistd.h>
- #include <iostream>
- using namespace std;
- const int MAX_THREADS = 10000;
- void* thread1(void *param)
- {
- char buff[1024] = {'\0'};
- cout << "I am ok" << buff << endl;
- }
- int main()
- {
- pthread_t pid[MAX_THREADS];
- for(int i = 0; i < MAX_THREADS; i++)
- {
- //设置线程分离属性
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
- pthread_create(&pid[i], &attr, thread1, NULL);
- sleep(1);
- }
- return 0;
- }
程序刚开始运行时内存截图:
程序运行一段时间后内存截图:
方法2:
- //test3.cc
- #include <iostream>
- #include <pthread.h>
- #include <unistd.h>
- #include <stdio.h>
- using namespace std;
- const int MAX_THREADS = 10000;
- void* thread1(void *param)
- {
- char buff[1024] = {'\0'};
- cout << "I am ok" << buff << endl;
- pthread_detach(pthread_self());
- }
- int main()
- {
- pthread_t pid[MAX_THREADS];
- for(int i = 0; i < MAX_THREADS; i++)
- {
- pthread_create(&pid[i], NULL, thread1, NULL);
- sleep(1);
- }
- return 0;
- }
程序刚开始运行时内存截图:
程序运行一段时间后内存截图:
- 解决使用pthread_create函数造成的内存泄露
- 解决使用pthread_create函数造成的内存泄露
- 解决使用pthread_create函数造成的内存泄露
- 避免使用不当pthread_create函数造成内存泄露
- Android使用Handler造成的内存泄露问题的解决
- Android中使用Handler造成内存泄露的分析和解决
- Android中使用Handler造成内存泄露的分析和解决
- Android中使用Handler造成内存泄露的分析和解决
- Android中使用Handler造成内存泄露的分析和解决
- Android中使用Handler造成内存泄露的分析和解决
- Android中使用Handler造成内存泄露的分析和解决
- Android中使用Handler造成内存泄露的分析和解决
- Android中使用Handler造成内存泄露的分析和解决
- Android中使用Handler造成内存泄露的分析和解决
- Android中使用Handler造成内存泄露的分析和解决
- Android中使用Handler造成内存泄露的分析和解决
- Android中使用Handler造成内存泄露的分析和解决
- 关于Android中使用Handler造成内存泄露的分析和解决
- 转:解析WS08 R2 SP1中的GPU虚拟化技术——RemoteFX
- 动态内存(2012.07.05)
- how does RemoteFX works?
- 从标准输入中读命令并执行
- 记录pdf文档上次打开的位置
- 解决使用pthread_create函数造成的内存泄露
- 2012.7.5计划
- 2012.7.4计划
- 2012-7-5
- tomcat 7中使用DWR报出跨域安全异常处理方法
- informix shell 定时执行数据库的存储过程
- 六月工作总结
- execl execlp execle execv execvp execve
- 使用c++标准io解析csv