pthread_join直接决定资源是否能够及时释放

/*http://hankjin.blog.163.com/blog/static/33731937201072675024100/
pthread的内存泄露  
# cc thread.c -lpthread
# ./a.out
1 threads created
101 threads created
201 threads created
301 threads created
ERROR, rc is 11, so far 382 threads created
Fail:: Resource temporarily unavailable
错误提示资源不足,其实是发生了内存泄露,在run函数中,使用pthread_exit退出的线程,并没有像预想的一样释放内存,而是进入僵死状态,只有进程退出的时候才能释放,要想让pthread_exit的线程及时退出,只要在pthread_create后加上pthread_join函数调用即可。只要有了pthread_join,即使没有调用pthread_exit,线程退出时也会释放内存。
也就是说pthread_exit只是线程的一个出口,和资源的释放无关,pthread_join直接决定资源是否能够及时释放。
*/
#include<pthread.h>
#include<stdio.h>
void *run(void*p) {
    pthread_exit(0); //可以不要,会自动调用
}

int main () {
    pthread_t thread;
    int rc;
    long count = 0;
    while(1) {
        if((rc=pthread_create(&thread, NULL, run,NULL))!=0) {
            printf("ERROR, rc is %d, %ld threads created\n", rc, count);
            perror("Fail:");
            return -1;
        }
        //pthread_join(thread,0);//阻塞主线程,等待id线程结束。
        if(count++%100==0)
            printf("%ld threads created\n", count);
    }
    return 0;//结束本进程内所有线程
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值