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);
}
因此,必须对每个创建为非分离的线程调用一次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);
}
相关文章推荐
- linux多线程学习(二)——线程的创建和退出
- 正确处理 Linux 平台下的线程结束问题
- 【原创】《Linux高级程序设计》杨宗德著 - Linux多线程编程 - 线程退出与等待
- Linux多线程(二)(线程等待,退出)
- linux 和 windows C++ 子线程编程中子线程的退出——总结
- linux多线程学习(二)——线程的创建和退出
- linux下的线程的创建退出及回收
- 正确得到线程退出信息的方法详解-变量存储退出信息结构、使用动态存储的方式退出信息结构、使用全局变量方式推相互信息结构、使用main函数中的局部变量存储退出信息结构
- 【Linux学习】pthread_create主线程与创建的新线程之间退出关系
- linux中线程如何退出
- Linux线程退出方式总结
- 【Linux学习】pthread_create主线程与创建的新线程之间退出关系
- Linux 线程退出实例1
- 【原创】《Linux高级程序设计》杨宗德著 - Linux多线程编程 - 线程退出与等待 分类: Linux --- 应用程序设计 2014-11-19 18:04 64人阅读 评论(0) 收藏
- 【Linux学习】pthread_create主线程与创建的新线程之间退出关系
- linux多线程学习(二)—线程的创建和退出
- linux多线程学习(二)——线程的创建和退出
- linux多线程学习(二)——线程的创建和退出
- linux线程的退出--附:一个变量,两个精彩
- linux下 c中怎么让才能安全关闭线程 和 linux线程退出时执行的程序(线程清理处理程序)简单例子