zl程序教程

您现在的位置是:首页 >  其它

当前栏目

pthread_join()与pthread_detach()

Join pthread detach
2023-09-11 14:21:13 时间

pthread_detach()即主线程与子线程分离,子线程结束后,资源自动回收。

pthread_join()即是子线程合入主线程,主线程阻塞等待子线程结束,然后回收子线程资源。

在任何一个时间点上,线程是可结合的(joinable)或者是分离的(detached)。一个可结合的线程能够被其他线程收回其资源和杀死。
在被其他线程回收之前,它的存储器资源(例如栈)是不释放的。相反,一个分离的线程是不能被其他线程回收或杀死的,它的存储器资源在它终止时由系统自动释放。
默认情况下,线程被创建成可结合的。为了避免存储器泄漏,每个可结合线程都应该要么被显示地回收,即调用pthread_join;要么通过调用pthread_detach函数被分离。
 

如果一个线程结束运行但没有被join,则它的状态类似于进程中的Zombie Process,即还有一部分资源没有被回收(退出状态码).

所以创建线程者应该调用pthread_join来等待线程运行结束,并可得到线程的退出代 码,回收其资源(类似于wait,waitpid) 。

但是调用pthread_join(pthread_id)后,如果该线程没有运行结束,调用者会被阻塞,在有些情况下我们并不希望如此。

比如在Web服务器中当主线程为每个新来的链接创建一个子线程进行处理的时候,主线程并不希望因为调用pthread_join而阻塞(因为还要继续处理之后到来的链接),这时可以在子线程中加入代码pthread_detach(pthread_self())。

或者父线程调用pthread_detach(thread_id)(非阻塞,可立即返回)   

这将该子线程的状态设置为detached,则该线程运行结束后会自动释放所有资源。

 pthread_t tid;
 int status = pthread_create(&tid, NULL, ThreadFunc, NULL);
 if(status != 0)
 {
  perror("pthread_create error");
 }
 pthread_detach(tid);
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
 
void *thread_function(void *arg)
{
  int i;
  for ( i=0; i<8; i++)
 {
    printf("Thread working...! %d \n",i);
    sleep(1);
  }
  return NULL;
}
 
int main(void)
{
  pthread_t mythread;
 
  if ( pthread_create( &mythread, NULL, thread_function, NULL) )
 {
    printf("error creating thread.");
    abort();
  }
  if ( pthread_join ( mythread, NULL ) )
 {
    printf("error join thread.");
    abort();
  }
 
  printf("thread done! \n");
  exit(0);
}