#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
void *f(void *arg)
{
int n = 3;
while (n--) {
printf("thread count %d\n", n);
sleep(1);
}
return (void *)1;
}
/*
* int pthread_detach(pthread_t tid);
* pthread_t tid:分离线程tid
* 返回值:成功返回0,失败返回错误号。
* 一般情况下,线程终止后,其终止状态一直保留到其它线程调用pthread_join获取它的状态为止。但是线程也可以被置为detach状态,这样的线程一旦终止就立刻回收
* 它占用的所有资源,而不保留终止状态。不能对一个已经处于detach状态的线程调用pthread_join,这样的调用将返回EINVAL。如果已经对一个线程调用了pthread_detach就不
* 能再调用pthread_join了。
*/
int main(void)
{
pthread_t tid;
void *tret = NULL;
int err = 0;
pthread_create(&tid, NULL, f, NULL);
//第一次运行时注释掉下面这行,第二次再打开,分析两次结果
pthread_detach(tid);
while (1) {
err = pthread_join(tid, &tret);
if (err != 0)
fprintf(stderr, "thread %s\n", strerror(err));
else
fprintf(stderr, "thread exit code %d\n", (int)tret);
sleep(1);
}
return 0;
}