您的位置:首页 > 运维架构 > Linux

linux线程退出正确姿势demo

2017-05-25 11:05 453 查看
当一个非分离的线程终止后,该线程的内存资源(线程描述符和栈)并不会被释放,直到有线程对它使 用了pthread_join时才被释放。

因此,必须对每个创建为非分离的线程调用一次pthread_join调用,以避免内存泄漏。否则当线程是可分 离的,调用pthread_exit,将终止该调用线程,并释放所有资源,没有线程等待它终止。

1、线程函数退出

#include<stdio.h>  

#include<unistd.h>  

#include<stdlib.h>  

#include<string.h>  

#include<pthread.h>  

void *func(void *arg)  

{  

  pthread_exit("Thread funtion finished!");//显示声明,线程退出,返回值为字符串

  //return (void *)2;//线程结束返回;隐式声明,线程退出



int main()  

{  

  int res;  

  pthread_t a_thread;  

  void *thread_res;  

  res = pthread_create(&a_thread,NULL,func,(void*)0);  

  if(res != 0)  

  {  

    perror("Fail to create a new thread");  

    exit(EXIT_FAILURE);  

  }  

  /*当一个线程通过调用pthread_exit()退出或者简单地从启动历程中返回时,进程中的其他线程可以通过调用pthread_join()函数获得进程的退出状态。调用pthread_join进程将一直阻塞,直到指定的线程调用pthread_exit,从启动例程中或者被取消。*/

  res = pthread_join(a_thread,(void*)&thread_res  /*NULL*/);  //也可以返回NULL;phread_join()等待一个线程终止

  if(res != 0)  

  {  

    perror("thread join error");  

    exit(EXIT_FAILURE);  

  }  

  printf("线程退出,捕获返回值 =  %s\n",(char *)thread_res);  

  printf("sizeof(void*) = %d",sizeof(void *));//打印出发现void *占了8个字节

  //printf("线程返回,捕获返回值 =  %ld\n",(long)thread_res); //所以用long类型转换而没有警告  

  exit(EXIT_SUCCESS);  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐