前几天看了APUE关于线程部分的内容,这部分介绍的比较少没太理解,再回头看的时候有点感悟,特此记录下来。
函数原型
#include <pthread.h>
int pthread_detach(pthread_t tid); //成功返回0;出错返回错误编号
功能说明
创建一个线程默认的状态是joinable, 如果一个线程结束运行但没有被join,则它的状态类似于进程中的Zombie Process,即还有一部分资源没有被回收(退出状态码),所以创建线程者应该pthread_join来等待线程运行结束,并可得到线程的退出代码,回收其资源。
实例分析
int
main(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) ;
}
在这种情况下,主线程会阻塞等待两个线程结束回收其资源
int
main(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,则该线程运行结束后会自动释放所有资源。
本文介绍了线程中pthread_detach和pthread_join的功能区别。当线程创建后,默认为可连接状态,通过调用pthread_join可以等待线程结束并回收资源;而调用pthread_detach则使线程变为分离状态,线程结束后自动释放资源。
831

被折叠的 条评论
为什么被折叠?



