日期:2014-05-16  浏览次数:20591 次

linux 创建线程资源回收不了
代码如下:

#include <pthread.h>   
#include<stdio.h>
#include <unistd.h>

void* run0()
{

usleep(5000);
printf("this is a thread\n");


}

int main()
{
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);//设置线程属性分离
pthread_attr_destroy(&attr);
pthread_create(&tid, &attr, run0, NULL);
usleep(6000);
printf("this ia  main thread\n");
}


我用 valgrind测试结果如下:= 136 bytes in 1 blocks are possibly lost in loss record 1 of 1
==2722==    at 0x4024F12: calloc (vg_replace_malloc.c:467)
==2722==    by 0x40117EB: _dl_allocate_tls (dl-tls.c:300)
==2722==    by 0x40426A9: pthread_create@@GLIBC_2.1 (allocatestack.c:570)
==2722==    by 0x8048629: main (test.c:21)
==2722== 
==2722== LEAK SUMMARY:
==2722==    definitely lost: 0 bytes in 0 blocks
==2722==    indirectly lost: 0 bytes in 0 blocks
==2722==      possibly lost: 136 bytes in 1 blocks
==2722==    still reachable: 0 bytes in 0 blocks
==2722==         suppressed: 0 bytes in 0 blocks
==2722== 
==2722== For counts of detected and suppressed errors, rerun with: -v
==2722== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 14 from 7)

按理说我已经设置的线程分离属性 线程结束回自己回收, 我用另一种方式 在线程函数加pthread_detach(pthread_self());或者在主线程加pthread_detach(tid) 测试出来任然是一样效果不知道这个是什么问题。 PS:不设置线程属性分离 用pthread_jion函数 择能后完全回收线程资源
求解

------解决方案--------------------
在分离属性情况下,一个线程结束时会立即释放它所占有的系统资源,但有一点要注意的是,如果设置一个线程分离属性,而这个线程又运行得非常快的话,那么它很可能在pthread_create函数返回之前就终止了线程函数的运行,它终止以后就很有可能将线程号和系统资源移交给其他的线程使用,这时调用pthread_create的线程就得到错误的线程号。

我觉得可能跟这个有关系。
你把那个usleep(5000);改大点如usleep(15000);试试吧。

------解决方案--------------------
在mian里加个while循环,先不让主进程结束,在看看你测试的结果!