zoukankan      html  css  js  c++  java
  • 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
    ", rc, count);
                perror("Fail:");
                return -1;
            }
            //pthread_join(thread,0);//阻塞主线程,等待id线程结束。
            if(count++%100==0)
                printf("%ld threads created
    ", count);
        }
        return 0;//结束本进程内所有线程
    }
  • 相关阅读:
    RESTful API设计指南(转载)
    理解RESTful架构(转载)
    什么是FreeMaker?
    为了梦,向前冲!
    php时间输出结果减去一分钟
    利用css+js制作下拉列表
    zzz的口胡记
    UOJ507. 【JOISC2020】星座3(贪心)
    vim使用小记
    UOJ#62【UR #5】怎样跑得更快(反演)
  • 原文地址:https://www.cnblogs.com/leijiangtao/p/3995765.html
Copyright © 2011-2022 走看看