线程终止(一)
线程
退出码
单线程的退出方法 :
- 从程序中正常退出, 返回线程的退出码.
- 被同一进程的其他线程取消.
- 线程调用pthread_exit()函数.
#include <pthread.h>
void pthread_exit(void *rval ptr)
// 从例程中返回, rval_ptr包含返回码. 如果线程被取消, 返回PTHREAD_CANCELED.
#include <pthread.h>
int pthread_join(pthread_t thread, void **rval_ptr) // 是一种屏障
// rval_ptr : 保存线程的返回码
// 将thread = NULL, 则对返回值无用;
// pthread_join等待指定的线程终止, 但并不获取线程的终止码
// 成功, 返回 0; 失败, 返回错误编码
在我看书的时候, 一直有这样一个疑问 :
pthread_exit与return的区别
- pthread_exit是可以进行推出的清理工作的,包括对局部类的析构。
- pthread_exit()用于线程退出,可以指定返回值,以便其他线程通过pthread_join()函数获取该线程的返回值
return,是函数返回,不一定是线程函数哦! 只有线程函数return,线程才会退出
为此, 我也自己找过方法, 网上的资料也看了, 最后自己总结出来了一段代码, 直接验证上述说的区别.
/*************************************************************************
> File Name: t.cpp
> Author: Function_Dou
> Mail:
> Created Time: 2018年03月05日 星期一 20时24分05秒
************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>
void *fun1(void)
{
pthread_exit((void *)1);
}
void *thread_fun1(void *)
{
fun1();
return ((void *)0);
}
void *fun2(void)
{
return ((void *)3);
}
void *thread_fun2(void *)
{
fun2();
pthread_exit((void *)2);
}
int main(void)
{
void *tret;
pthread_t tid1, tid2;
// 建立第一个线程
if((errno = pthread_create(&tid1, NULL, thread_fun1, NULL)) != 0)
fprintf(stderr, "pthread_create error : %s\n", strerror(errno));
if((errno = pthread_join(tid1, &tret)) != 0)
fprintf(stderr, "pthread_join error : %s\n", strerror(errno));
// 第一个的返回码
printf("tid1 : %ld\n", (long)tret);
// 建立第二个线程
if((errno = pthread_create(&tid2, NULL, thread_fun2, NULL)) != 0)
fprintf(stderr, "pthread_create error : %s\n", strerror(errno));
if((errno = pthread_join(tid2, &tret)) != 0)
fprintf(stderr, "pthread_join error : %s\n", strerror(errno));
// 第二个的返回码
printf("tid2 : %ld\n", (long)tret);
exit(0);
}
运行结果 : 你会发现, 线程的结束是pthread_exit()函数控制的, 而不是return代表线程结束
[root@localhost Pthread]# ./a.out
tid1 : 1
tid2 : 2