• linux下线程的分离和结合属性


    在任何一个时间点上,线程是可结合的(joinable),或者是分离的(detached)。一个可结合的线程能够被其他线程收回其资源和杀死;在被其他线程回收之前,它的存储器资源(如栈)是不释放的。相反,一个分离的线程是不能被其他线程回收或杀死的,它的存储器资源在它终止时由系统自动释放。

    默认情况下,线程被创建成可结合的。为了避免存储器泄漏,每个可结合线程都应该要么被显示地回收,即调用pthread_join;要么通过调用pthread_detach函数被分离。如果一个可结合线程结束运⾏行但没有被join,则它的状态类似于进程中的Zombie Process, 即还有一部分资源没有被回收,所以创建线程者应该调用pthread_join来等待线程运行结束,并可得到线程的退出代码,回收其资源。 由于调用pthread_join后,如果该线程没有运行结束,调用者会被阻塞,在有些情况下我们并不希望如此。例如,在Web服务器中当主线程为每个新来的连接请求创建一个子线程进 行处理的时候,主线程并不希望因为调用pthread_join而阻塞(因为还要继续处理之后到来 的连接请求), 这时可以在子线程中加入代码:

    pthread_detach(pthread_self());
    

    或者父线程调用时加入:

    pthread_detach(thread_id)
    

    这将该子线程的状态设置为分离的(detached),如此一来,该线程运⾏行结束后会自动释 放所有资源。

    代码示例:

    #include<stdio.h>
    #include<pthread.h>
    #include<unistd.h>
    #include<sys/types.h>
    
    void* pthread_running(void *_val)
    { 
        pthread_detach(pthread_self());
        printf("%s
    ", (char*)_val);
        return NULL;
    }
    
    int main()
    { 
        pthread_t tid;
        int ret = pthread_create(&tid, NULL, pthread_running, "main thread is running");
    
        if(ret != 0)
        { 
            printf("create thread error! info is:%s
    ", strerror(ret));
            return ret;
        }
    
        int temp = 0;
        sleep(1);
        if(0 == pthread_join(tid, NULL))
        { 
            printf("pthread wait success!
    ");
            temp = 0;
        }
        else
        { 
            printf("pthread wait failed!
    ");
            temp = 1;
        }
    
        return temp;
    }
    

    运行结果:

  • 相关阅读:
    vue---echarts图表
    路由嵌套
    VoIP语音通话研究【进阶篇(四):freeswitch+webrtc+sip.js的通话】
    VoIP语音通话研究【进阶篇(三):opensips安装】
    如何在北京退休?
    后端分析/前端分析/边缘分析
    使用curl批量下载图片
    pytorch固定随机种子复现实验结果
    分享一个作为面试官的面试思路
    两个流程链路问题的排查和总结
  • 原文地址:https://www.cnblogs.com/chay/p/10587459.html
Copyright © 2020-2023  润新知