5.2 线程的分离
  有时我们并不在乎某个线程是不是已经终止了,我们只是希望如果某个线程终止了,系统能自动回收掉该终止线程所占用的资源。pthread_detach函数为我们提供了这个功能,该功能称为线程的分离:
  #include <pthread.h>
  int pthread_detach(pthread_t thread);
  默认情况下,一个线程终止了,是需要在被连接后系统才能回收其占有的资源的。如果我们调用pthread_detach函数去分离某个线程,那么该线程终止后系统将自动回收其资源。
/*
* 文件名: thread_sample1.c
* 描述:演示线程基本操作
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
/*子线程1入口函数*/
void *thread_routine1(void *arg)
{
fprintf(stdout, "thread1: hello world! ");
sleep(1);
/*子线程1在此退出*/
return NULL;
}
/*子线程2入口函数*/
void *thread_routine2(void *arg)
{
fprintf(stdout, "thread2: I'm running... ");
pthread_t main_thread = (pthread_t)arg;
/*分离自我,不能再被连接*/
pthread_detach(pthread_self());
/*判断主线程ID与子线程2ID是否相等*/
if (!pthread_equal(main_thread, pthread_self())) {
fprintf(stdout, "thread2: main thread id is not equal thread2 ");
}
/*等待主线程终止*/
pthread_join(main_thread, NULL);
fprintf(stdout, "thread2: main thread exit! ");
fprintf(stdout, "thread2: exit! ");
fprintf(stdout, "thread2: process exit! ");
/*子线程2在此终止,进程退出*/
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
/*创建子线程1*/
pthread_t t1;
if (pthread_create(&t1, NULL, thread_routine1, NULL)!=0) {
fprintf(stderr, "create thread fail. ");
exit(-1);
}
/*等待子线程1终止*/
pthread_join(t1, NULL);
fprintf(stdout, "main thread: thread1 terminated! ");
/*创建子线程2,并将主线程ID传递给子线程2*/
pthread_t t2;
if (pthread_create(&t2, NULL, thread_routine2, (void *)pthread_self())!=0) {
fprintf(stderr, "create thread fail. ");
exit(-1);
}
fprintf(stdout, "main thread: sleeping... ");
sleep(3);
/*主线程使用pthread_exit函数终止,进程继续存在*/
fprintf(stdout, "main thread: exit! ");
pthread_exit(NULL);
fprintf(stdout, "main thread: never reach here! ");
return 0;
}
  终的执行结果如下:
thread1: hello world!
main thread: thread1 terminated!
main thread: sleeping...
thread2: I'm running...
thread2: main thread id is not equal thread2
main thread: exit!
thread2: main thread exit!
thread2: exit!
thread2: process exit!