1 pthread_detach函数
int pthread_detach(pthread_t thread);
/*
功能:
1)实现线程分离,不再受主线程管理,由系统接任。线程结束后,其退出状态不由其他线程获取,而直接自己自动释放。网络、多线程服务器常用。
对比进程:进程若有该机制,将不会产生僵尸进程。僵尸进程的产生主要由于进程死后,大部分资源被释放,一点残留资源仍存于系统中,导致内核认为该进程仍存在。
对比pthread_create:也可使用pthread_create函数参2(线程属性)来设置线程分离。
成功:0;失败:错误号。
参1:线程id。
*/
2 错误返回值分析
注意,所有线程的错误号返回都只能使用strerror这个函数判断,不能使用perror,因为perror是调用进程的全局错误号,不适合单独线程的错误分析,所以只能使用strerror。
3 pthread_detach案例
线程可以被置为detach状态,这样的线程一旦终止就立刻回收它占用的所有资源,而不保留终止状态。不能对一个已经处于detach状态的线程调用pthread_join,这样的调用将返回EINVAL错误。也就是说,如果已经对一个线程调用了pthread_detach就不能再调用pthread_join了。
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
void *thrd_func(void *arg)
{
printf("i am detach.\n");
pthread_exit((void *)77);
}
int main(void)
{
pthread_t tid;
int ret;
ret = pthread_create(&tid, NULL, thrd_func, NULL);
if (ret != 0) {
fprintf(stderr, "pthread_create error:%s\n", strerror(ret));
exit(1);
}
ret = pthread_detach(tid);
if (ret != 0) {
fprintf(stderr, "pthread_detach error:%s\n", strerror(ret));
exit(1);
}
sleep(1);
printf("main pid=%d, tid=&lu\n", getpid(), pthread_self());
pthread_exit((void *)0);
}
4 pthread_detach总结
- 1)注意,所有线程的错误号返回都只能使用strerror这个函数判断,不能使用perror,因为perror是调用进程的全局错误号,不适合单独线程的错误分析,所以只能使用strerror。
- 2)线程可以被置为detach状态,这样的线程一旦终止就立刻回收它占用的所有资源,而不保留终止状态。不能对一个已经处于detach状态的线程调用pthread_join,这样的调用将返回EINVAL错误。也就是说,如果已经对一个线程调用了pthread_detach就不能再调用pthread_join了。