- 论坛徽章:
- 0
|
最近我写一个简单的小程序,会不断的创建线程.跑个十多天,内存涨了很多.起初怀疑是malloc问题,但没有找到.
后来我怀疑是线程有没有退出的,发现也不是.然后我才发现是线程退出了,而内存没有释放...
请看示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
void * _thread(void *argv)
{
printf("###thread[%d] running...\n",pthread_self());
sleep(10);
printf("###thread[%d] END...\n",pthread_self());
return (void *)0;
}
int main(int argc, char **argv)
{
pthread_t thrd;
int result,rt;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, (int)(1024 * 1024 * 3.5 ) ); // <--请改变栈大小测试
sleep(10);
int i;
for(i=0;i<10;i++)
{
result = pthread_create(&thrd,&attr,_thread,(void*)0);
if(result)
printf("thread created error...\n");
else
{
printf("thread created =%d\n",thrd);
rt=pthread_detach(thrd);
if (rt)
printf("pthread_detach error\n");
}
}
pthread_attr_destroy(&attr);
sleep(300);
return 0;
}
|
我测试的结果是:
当栈在3.5M以下时候,线程退出基本不会释放内存;
当栈在10M时候,退出大约会释放60%的内存;
当栈在20M以上时候,退出大约会释放90%的内存
这就郁闷了,我的程序内存越来越大,怎么办?
大家是怎么解决的?还是我在哪里处理有问题?
谢谢大家~~~
[ 本帖最后由 superdbs 于 2009-8-6 11:29 编辑 ] |
|