线程是可结合的(joinable)或者是分离的(detached)。一个可结合的线程能够被其他线程收回其资源和杀死。在被其他线程回收之前,它的存储器资源(例如栈)是不释放的。相反,一个分离的线程是不能被其他线程回收或杀死的,它的存储器资源在它终止时由系统自动释放。


默认情况下,线程被创建成可结合的。为了避免存储器泄漏,每个可结合线程都应该要么被显示地回收,即调用pthread_join;要么通过调用pthread_detach函数被分离。


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


由于调用pthread_join后,如果该线程没有运行结束,调用者会被阻塞,在有些情况下我们并不希望如此。例如,在Web服务器中当主线程为每个新来的连接请求创建一个子线程进行处理的时候,主线程并不希望因为调用pthread_join而阻塞(因为还要继续处理之后到来的连接请求),这时可以在子线程中加入代码。

pthread_detach(pthread_self())

或者父线程调用

pthread_detach(thread_id)(非阻塞,可立即返回)

这将该子线程的状态设置为分离的(detached),如此一来,该线程运行结束后会自动释放所有资源。

  1 #include<stdio.h>
  2 #include<pthread.h>
  3 #include<stdlib.h>
  4 #include<string.h>
  5 
  6 void* pthread_run1(void* arg)
  7 {
  8 pthread_detach(pthread_self());
  9     printf("this is a thread1,pid:%d,tid:%ld\n",getpid(),pthread_self());
 10     return NULL;
 11 }
 12 int main()
 13 {
 14     pthread_t tid;
 15 
 16     int err=pthread_create(&tid,NULL,pthread_run1,NULL);
 17     if(err!=0)
 18     {
 19      printf("%s\n",strerror(err));
 20      return  -1;
 21     }
 22     int ret=0;
 23     sleep(2);
  24     if(0==pthread_join(tid,NULL))
  25     {
  26     printf("wait success\n");
  27     ret=0;
  28     }
  29     else
  30     {
  31     printf("wait failure\n");
  32      ret=1;
  33     }
  34     return ret;
  35 }
  
  
 结果:
[admin@localhost THREAD]$ vim detach.c
[admin@localhost THREAD]$ gcc -o detach detach.c -lpthread
[admin@localhost THREAD]$ ./detach
this is a thread1,pid:3800,tid:-1216599184
wait failure