多线程程序中,终止线程执行的方式有 3 种,分别是:
- 线程执行完成后,自行终止;
- 线程执行过程中遇到了
pthread_exit()
或者return
,也会终止执行; - 线程执行过程中,接收到其它线程发送的 “终止执行” 的信号,然后终止执行。
三种方式中,第一种很容易理解,本节重点给大家讲解后两种方法。
1. pthread_exit()
在 C 语言中,return
关键字用于终止函数执行,必要时还能将函数的执行结果反馈给调用者。return
关键字不仅可以用于普通函数,线程函数中也可以使用它。
<pthread.h>
头文件中,提供有一个和 return
关键字相同功能的 pthread_exit()
函数。和之前不同,pthread_exit()
函数只适用于线程函数,而不能用于普通函数。
pthread_exit()
函数的语法格式如下:
void pthread_exit(void *retval);
retval 是void*
类型的指针,可以指向任何类型的数据,它指向的数据将作为线程退出时的返回值。如果线程不需要返回任何数据,将 retval 参数置为NULL
即可。
注意,retval 指针不能指向函数内部的局部数据(比如局部变量)。换句话说,
pthread_exit()
函数不能返回一个指向局部数据的指针,否则很可能使程序运行结果出错甚至崩溃。
通过一个样例,给大家演示 pthread_exit()
函数的用法(样例一):
#include <stdio.h>
#include <pthread.h>
void *ThreadFun(void *arg) {
// pthread_exit() 执行线程的执行,将 "这时线程返回值" 返回
// 该返回的字符串存储在常量区,并非当前线程的私有资源
pthread_exit("这是线程返回值");
printf("*********"); // 此语句不会被线程执行
}
int main() {
int res;
void *thread_result;
pthread_t myThread;
// 创建线程:myThread
res = pthread_create(&myThread, NULL, ThreadFun, NULL);
if (res !=0 ) {
printf("线程创建失败\n");
return 0;
}
// 等待myThread线程执行完成,并用thread_result指针接收线程myThread的返回值
res = pthread_join(myThread, &thread_result);
if (res != 0) {
printf("等待线程失败\n");
}
printf("%s\n", (char*)thread_result);
return 0;
}
一个由 C/C++ 编译的程序占用的内存分为以下几个部分:
- 栈区 (stack):由编译器自动分配释放,存放函数的参数值、局部变量的值等,其操作方式类似于数据结构中的栈;
- 堆区 (heap):一般由程序员分配(
new
和malloc
)和释放(delete
和free
)。若程序员不释放,程序结束时可能由 OS 回收,但会导致内存泄漏,严重的导致系统崩溃,入一个程序是长期运行的,申请的变量永远得不到释放,系统内存会耗尽,分配方式类似于链表。- 全局区 (静态区,static):全局变量和静态变量的存储是放在一块的,初始化的全局变量和静态变量在一块区域,未初始化的全局变量和静态变量在相邻的另一块区域,程序结束后由 OS 释放。
- 文字常量区:常量字符串就是放在这里的,程序结束后由 OS 释放。
- 程序代码区:存放函数体的二进制代码。
假设程序存储在 thread.c 文件中,执行过程如下:
[root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# gcc thread.c -o thread -lpthread
[root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# ./thread
这是线程返回值
不难看出,myThread 线程并没有执行 ThreadFun()
函数中最后一个 printf("**************")
语句,从侧面验证了 pthread_exit()
函数的功能。此外,我们通过在主线程(main()
函数)调用 pthread_join()
函数,获取到了 myThread 线程返回的数据。
有关
pthread_join()
函数的功能和用法,我们会在《获取线程函数的返回值》一节中给大家讲解。
2. pthread_exit()和return的区别
修改样例一中的程序,将第ThreadFun()
函数中的代码替换成如下语句:
void *ThreadFun(void *arg) {
// 使用 return 代替 pthread_exit()
return("这是线程返回值");
printf("*********"); // 此语句不会被线程执行
}
重新编译、执行此程序,会发现程序的执行结果和之前完全相同。这意味着当线程执行结束时,无论是采用 return语句还是调用
pthread_exit()函数,主线程中的
pthread_join()` 函数都可以接收到线程的返回值。
这就产生了一个问题,既然 return 关键字也适用于线程函数,
首先,return 语句和
pthread_exit()
函数的含义不同,return 的含义是返回,它不仅可以用于线程执行的函数,普通函数也可以使用;pthread_exit()
函数的含义是线程退出,它专门用于结束某个线程的执行。
在主线程(main()
函数)中,return 和 pthread_exit()
函数的区别最明显。举个例子:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *ThreadFun(void *arg) {
sleep(5); // 等待一段时间
printf("I'm hamstercoder\n");
}
int main() {
int res;
pthread_t myThread;
res = pthread_create(&myThread, NULL, ThreadFun, NULL);
if (res != 0) {
printf("线程创建失败");
return 0;
}
printf("我是程序员\n");
return 0;
}
编译、执行此程序,输出结果为:
[root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# gcc thread.c -o thread -lpthread
[root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# ./thread
我是程序员
通过执行结果可以看到,主线程正常执行结束,myThread 线程并没有输出指定的数据。原因很简单,主线程执行速度很快,主线程最后执行的 return 语句不仅会终止主线程执行,还会终止其它子线程执行。也就是说,myThread 线程还没有执行输出语句就被终止了。
将上面程序中,main() 函数中的
return 0;
用语句 pthread_exit(NULL);
替换:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *ThreadFun(void *arg) {
sleep(5); // 等待一段时间
printf("I'm hamstercoder\n");
}
int main() {
int res;
pthread_t myThread;
res = pthread_create(&myThread, NULL, ThreadFun, NULL);
if (res != 0) {
printf("线程创建失败");
return 0;
}
printf("我是程序员\n");
pthread_exit(NULL);
}
重新编译、执行程序,运行结果为:
[root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# gcc thread.c -o thread -lpthread
[root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# ./thread
我是程序员
I'm hamstercoder
对比上面两个执行结果,可以得出的结论是:pthread_exit()
函数只会终止当前线程,不会影响其它线程的执行。
此外,
pthread_exit()
函数还会自动调用线程清理程序(本质是一个由pthread_cleanup_push()
指定的自定义函数),而 return 不具备这个能力。
总之,如果实际场景中想终止某个子线程,强烈建议大家使用 pthread_exit()
函数。终止主线程时,return 和 pthread_exit()
函数发挥的功能不同,可以根据需要自行选择。
3. pthread_cancel()
多线程程序中,一个线程还可以向另一个线程发送 “终止执行” 的信号(后续称 “Cancel” 信号),这时就需要调用 pthread_cancel()
函数。
pthread_cancel()
函数声明在<pthread.h>
头文件中,语法格式如下:
int pthread_cancel(pthread_t thread);
参数 thread 用于接收 Cancel 信号的目标线程。
如果 pthread_cancel()
函数成功地发送了 Cancel 信号,返回数字 0,否则返回非零数。对于因 “未找到目标线程” 导致的信号发送失败,函数返回 ESRCH 宏(定义在<errno.h>
头文件中,该宏的值为整数 3)。
注意,
pthread_cancel()
函数的功能仅仅是向目标线程发送 Cancel 信号,至于目标线程是否接收该信号,何时响应该信号,全由目标线程决定。我们会在《终止线程执行,千万别踩这个坑!》一节给您做详细讲解。
对于接收 Cancel 信号后结束执行的目标线程,等同于该线程自己执行如下语句:
pthread_exit(PTHREAD_CANCELED);
也就是说,当一个线程被强制终止执行时,它会返回PTHREAD_CANCELED
这个宏(定义在<pthread.h>
头文件中)。
接下来通过一个样例,给大家演示 pthread_cancel()
函数的用法:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
void *thread_Fun(void *arg) {
printf("新建线程开始执行\n");
sleep(10);
}
int main() {
pthread_t myThread;
void *mess;
int value;
int res;
res = pthread_create(&myThread, NULL, thread_Fun, NULL);
if (res != 0) {
printf("线程创建失败\n");
return 0;
}
sleep(1);
res = pthread_cancel(myThread); // 向myThread线程发送Cancel信号
if (res != 0) {
printf("终止myThread线程失败\n");
return 0;
}
res = pthread_join(myThread, &mess); // 获取已终止线程的返回值
if (res != 0) {
printf("等待线程失败\n");
return 0;
}
if (mess == PTHREAD_CANCELED) { // 如果线程被强制终止,其返回值为PTHREAD_CANCELED
printf("myThread线程被强制终止\n");
}
else {
printf("error\n");
}
return 0;
}
假设程序编写在 thread.c 文件中,执行过程为:
[root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# gcc thread.c -o thread -lpthread
[root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# ./thread
新建线程开始执行
myThread线程被强制终止