关于pthread_detach

来源:互联网 发布:程序员教程 第4版 pdf 编辑:程序博客网 时间:2024/06/05 14:44

前几天看了APUE关于线程部分的内容,这部分介绍的比较少没太理解,再回头看的时候有点感悟,特此记录下来。

函数原型

#include <pthread.h>int pthread_detach(pthread_t tid); //成功返回0;出错返回错误编号

功能说明

创建一个线程默认的状态是joinable, 如果一个线程结束运行但没有被join,则它的状态类似于进程中的Zombie Process,即还有一部分资源没有被回收(退出状态码),所以创建线程者应该pthread_join来等待线程运行结束,并可得到线程的退出代码,回收其资源。

实例分析

intmain(void){    int       err ;    pthread_t tid ;    //创建线程    if ((err = pthread_create(&tidbuf[0], NULL, thr1, NULL)) != 0)        perror("can't create thread!\n") ;    if ((err = pthread_create(&tidbuf[1], NULL, thr2, NULL)) != 0)        perror("can't create thread!\n") ;    //等待线程结束    pthread_join(tidbuf[0], NULL) ;    pthread_join(tidbuf[1], NULL) ;    exit(0) ;}

在这种情况下,主线程会阻塞等待两个线程结束回收其资源

intmain(void){    int       err ;    pthread_t tid ;    //创建线程    if ((err = pthread_create(&tidbuf[0], NULL, thr1, NULL)) != 0)        perror("can't create thread!\n") ;    if ((err = pthread_create(&tidbuf[1], NULL, thr2, NULL)) != 0)        perror("can't create thread!\n") ;    //非阻塞,可立即返回    pthread_detach(tidbuf[0]) ;    pthread_detach(tidbuf[1]) ;    exit(0) ;}

这将该子线程的状态设置为detached,则该线程运行结束后会自动释放所有资源。

0 0