多线程程序中,终止线程执行的方式有 3 种,分别是:

  1. 线程执行完成后,自行终止;
  2. 线程执行过程中遇到了 pthread_exit() 或者 return,也会终止执行;
  3. 线程执行过程中,接收到其它线程发送的 “终止执行” 的信号,然后终止执行。

三种方式中,第一种很容易理解,本节重点给大家讲解后两种方法。

1. pthread_exit()

在 C 语言中,return 关键字用于终止函数执行,必要时还能将函数的执行结果反馈给调用者。return 关键字不仅可以用于普通函数,线程函数中也可以使用它。

<pthread.h> 头文件中,提供有一个和 return 关键字相同功能的 pthread_exit() 函数。和之前不同,pthread_exit() 函数只适用于线程函数,而不能用于普通函数。

pthread_exit() 函数的语法格式如下:

  1. void pthread_exit(void *retval);

retval 是void*类型的指针,可以指向任何类型的数据,它指向的数据将作为线程退出时的返回值。如果线程不需要返回任何数据,将 retval 参数置为NULL即可。

注意,retval 指针不能指向函数内部的局部数据(比如局部变量)。换句话说,pthread_exit() 函数不能返回一个指向局部数据的指针,否则很可能使程序运行结果出错甚至崩溃。

通过一个样例,给大家演示 pthread_exit() 函数的用法(样例一):

  1. #include <stdio.h>
  2. #include <pthread.h>
  3. void *ThreadFun(void *arg) {
  4. // pthread_exit() 执行线程的执行,将 "这时线程返回值" 返回
  5. // 该返回的字符串存储在常量区,并非当前线程的私有资源
  6. pthread_exit("这是线程返回值");
  7. printf("*********"); // 此语句不会被线程执行
  8. }
  9. int main() {
  10. int res;
  11. void *thread_result;
  12. pthread_t myThread;
  13. // 创建线程:myThread
  14. res = pthread_create(&myThread, NULL, ThreadFun, NULL);
  15. if (res !=0 ) {
  16. printf("线程创建失败\n");
  17. return 0;
  18. }
  19. // 等待myThread线程执行完成,并用thread_result指针接收线程myThread的返回值
  20. res = pthread_join(myThread, &thread_result);
  21. if (res != 0) {
  22. printf("等待线程失败\n");
  23. }
  24. printf("%s\n", (char*)thread_result);
  25. return 0;
  26. }

一个由 C/C++ 编译的程序占用的内存分为以下几个部分:

  1. 栈区 (stack):由编译器自动分配释放,存放函数的参数值、局部变量的值等,其操作方式类似于数据结构中的栈;
  2. 堆区 (heap):一般由程序员分配( newmalloc)和释放(deletefree)。若程序员不释放,程序结束时可能由 OS 回收,但会导致内存泄漏,严重的导致系统崩溃,入一个程序是长期运行的,申请的变量永远得不到释放,系统内存会耗尽,分配方式类似于链表。
  3. 全局区 (静态区,static):全局变量和静态变量的存储是放在一块的,初始化的全局变量和静态变量在一块区域,未初始化的全局变量和静态变量在相邻的另一块区域,程序结束后由 OS 释放。
  4. 文字常量区:常量字符串就是放在这里的,程序结束后由 OS 释放。
  5. 程序代码区:存放函数体的二进制代码。

§ 4.线程终止执行的三种方法(Linux) - 图1

假设程序存储在 thread.c 文件中,执行过程如下:

  1. [root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# gcc thread.c -o thread -lpthread
  2. [root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# ./thread
  3. 这是线程返回值

不难看出,myThread 线程并没有执行 ThreadFun() 函数中最后一个 printf("**************") 语句,从侧面验证了 pthread_exit() 函数的功能。此外,我们通过在主线程(main() 函数)调用 pthread_join() 函数,获取到了 myThread 线程返回的数据。

有关 pthread_join() 函数的功能和用法,我们会在《获取线程函数的返回值》一节中给大家讲解。

2. pthread_exit()和return的区别

修改样例一中的程序,将第ThreadFun() 函数中的代码替换成如下语句:

  1. void *ThreadFun(void *arg) {
  2. // 使用 return 代替 pthread_exit()
  3. return("这是线程返回值");
  4. printf("*********"); // 此语句不会被线程执行
  5. }

重新编译、执行此程序,会发现程序的执行结果和之前完全相同。这意味着当线程执行结束时,无论是采用 return语句还是调用pthread_exit()函数,主线程中的pthread_join()` 函数都可以接收到线程的返回值。

这就产生了一个问题,既然 return 关键字也适用于线程函数, 头文件为什么还提供 pthread_exit() 函数,不是多此一举吗?

§ 4.线程终止执行的三种方法(Linux) - 图2 首先,return 语句和 pthread_exit() 函数的含义不同,return 的含义是返回,它不仅可以用于线程执行的函数,普通函数也可以使用;pthread_exit() 函数的含义是线程退出,它专门用于结束某个线程的执行。

在主线程(main() 函数)中,return 和 pthread_exit() 函数的区别最明显。举个例子:

  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. void *ThreadFun(void *arg) {
  5. sleep(5); // 等待一段时间
  6. printf("I'm hamstercoder\n");
  7. }
  8. int main() {
  9. int res;
  10. pthread_t myThread;
  11. res = pthread_create(&myThread, NULL, ThreadFun, NULL);
  12. if (res != 0) {
  13. printf("线程创建失败");
  14. return 0;
  15. }
  16. printf("我是程序员\n");
  17. return 0;
  18. }

编译、执行此程序,输出结果为:

  1. [root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# gcc thread.c -o thread -lpthread
  2. [root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# ./thread
  3. 我是程序员

通过执行结果可以看到,主线程正常执行结束,myThread 线程并没有输出指定的数据。原因很简单,主线程执行速度很快,主线程最后执行的 return 语句不仅会终止主线程执行,还会终止其它子线程执行。也就是说,myThread 线程还没有执行输出语句就被终止了。

§ 4.线程终止执行的三种方法(Linux) - 图3 将上面程序中,main() 函数中的return 0;用语句 pthread_exit(NULL); 替换:

  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. void *ThreadFun(void *arg) {
  5. sleep(5); // 等待一段时间
  6. printf("I'm hamstercoder\n");
  7. }
  8. int main() {
  9. int res;
  10. pthread_t myThread;
  11. res = pthread_create(&myThread, NULL, ThreadFun, NULL);
  12. if (res != 0) {
  13. printf("线程创建失败");
  14. return 0;
  15. }
  16. printf("我是程序员\n");
  17. pthread_exit(NULL);
  18. }

重新编译、执行程序,运行结果为:

  1. [root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# gcc thread.c -o thread -lpthread
  2. [root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# ./thread
  3. 我是程序员
  4. 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>头文件中,语法格式如下:

  1. int pthread_cancel(pthread_t thread);

参数 thread 用于接收 Cancel 信号的目标线程。

如果 pthread_cancel() 函数成功地发送了 Cancel 信号,返回数字 0,否则返回非零数。对于因 “未找到目标线程” 导致的信号发送失败,函数返回 ESRCH 宏(定义在<errno.h>头文件中,该宏的值为整数 3)。

注意,pthread_cancel() 函数的功能仅仅是向目标线程发送 Cancel 信号,至于目标线程是否接收该信号,何时响应该信号,全由目标线程决定。我们会在《终止线程执行,千万别踩这个坑!》一节给您做详细讲解。

对于接收 Cancel 信号后结束执行的目标线程,等同于该线程自己执行如下语句:

  1. pthread_exit(PTHREAD_CANCELED);

也就是说,当一个线程被强制终止执行时,它会返回PTHREAD_CANCELED这个宏(定义在<pthread.h>头文件中)。

接下来通过一个样例,给大家演示 pthread_cancel() 函数的用法:

  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. void *thread_Fun(void *arg) {
  6. printf("新建线程开始执行\n");
  7. sleep(10);
  8. }
  9. int main() {
  10. pthread_t myThread;
  11. void *mess;
  12. int value;
  13. int res;
  14. res = pthread_create(&myThread, NULL, thread_Fun, NULL);
  15. if (res != 0) {
  16. printf("线程创建失败\n");
  17. return 0;
  18. }
  19. sleep(1);
  20. res = pthread_cancel(myThread); // 向myThread线程发送Cancel信号
  21. if (res != 0) {
  22. printf("终止myThread线程失败\n");
  23. return 0;
  24. }
  25. res = pthread_join(myThread, &mess); // 获取已终止线程的返回值
  26. if (res != 0) {
  27. printf("等待线程失败\n");
  28. return 0;
  29. }
  30. if (mess == PTHREAD_CANCELED) { // 如果线程被强制终止,其返回值为PTHREAD_CANCELED
  31. printf("myThread线程被强制终止\n");
  32. }
  33. else {
  34. printf("error\n");
  35. }
  36. return 0;
  37. }

假设程序编写在 thread.c 文件中,执行过程为:

  1. [root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# gcc thread.c -o thread -lpthread
  2. [root@iZbp18vd1p2tytbwn5vgaqZ CPlusPlus]# ./thread
  3. 新建线程开始执行
  4. myThread线程被强制终止