linux中pthread_join()与pthread_detach()详解

 
 
 
 
前言:
1.linux线程执行和windows不同,pthread有两种状态joinable状态和unjoinable状态,如果线程是joinable状态,当线程函数自己返回退出时或pthread_exit时都不会释放线程所占用堆栈和线程描述符(总计8K多)。只有当你调用了pthread_join之后这些资源才会被释放。若是unjoinable状态的线程,这些资源在线程函数退出时或pthread_exit时自动会被释放。
2.unjoinable属性可以在pthread_create时指定,或在线程创建后在线程中pthread_detach自己, 如:pthread_detach(pthread_self()),将状态改为unjoinable状态,确保资源的释放。或者将线程置为 joinable,然后适时调用pthread_join.
3.其实简单的说就是在线程函数头加上 pthread_detach(pthread_self())的话,线程状态改变,在函数尾部直接 pthread_exit线程就会自动退出。省去了给线程擦屁股的麻烦。
 
 
detach线程创建:
     pthread_t tid;
     int status = pthread_create(&tid, NULL, ThreadFunc, NULL);
     if(status != 0)
     {
          perror("pthread_create error");
     }
     pthread_detach(tid)
 
 
小结:
创建分离线程:
    再线程创建时,将其属性设为分离状态(detached);
    再创建线程后,将其属性设置为分离得
分离线程得好处:
    由系统负责回收线程所占得资源
 
 
一:pthread_join()
(1)pthread_join()即是子线程合入主线程,主线程阻塞等待子线程结束,然后回收子线程资源。
(2)函数说明
  • 头文件 : #include <pthread.h>
  • 函数定义: int pthread_join(pthread_t thread, void **retval);
  • 描述 :pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果线程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
  • 参数 :thread: 线程标识符,即线程ID,标识唯一线程。retval: 用户定义的指针,用来存储被等待线程的返回值。
  • 返回值 : 0代表成功。 失败,返回的则是错误号。
 
实例:
#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);
}
 
 
 
 
posted @ 2020-12-19 21:25  dos_hello_world  阅读(364)  评论(0)    收藏  举报