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;//结束本进程内所有线程
    }
  • 相关阅读:
    从 PHP 到 Java
    用Lua定制Redis命令
    见招拆招-PostgreSQL中文全文索引效率优化
    通过2-3-4树理解红黑树
    代码迁移之旅(二)- 渐进式迁移方案
    多线程编程
    Gotorch
    使用PostgreSQL进行中文全文检索
    代码重构之旅(一) 项目结构
    Linux“体检”指标
  • 原文地址:https://www.cnblogs.com/leijiangtao/p/3995765.html
Copyright © 2011-2022 走看看