线程结束执行的 3 种方式中,第 1 种很容易理解,我们会在《pthread_cancel()函数》一文中介绍第 2 种方式,本文重点讲解 pthread_exit() 函数的功能和用法。实现线程资源及时回收的常用方法有两种,一种是修改线程属性,另一种是在另一个线程中调用 pthread_join() 函数,我们会在后续章节中给您详细介绍这两种方法。
<pthread.h>
头文件中,语法格式如下所示:
void pthread_exit(void *retval);retval 是 void* 类型的指针,可以指向任何类型的数据,它指向的数据将作为线程退出时的返回值。如果线程不需要返回任何数据,将 retval 参数置为 NULL 即可。
#include <stdio.h> #include <pthread.h> //线程要执行的函数,arg 用来接收线程传递过来的数据 void *ThreadFun(void *arg) { //终止线程的执行,将“http://c.biancheng.net”返回 pthread_exit("http://c.biancheng.net"); //返回的字符串存储在常量区,并非当前线程的私有资源 printf("*****************");//此语句不会被线程执行 } int main() { int res; //创建一个空指针 void * thread_result; //定义一个表示线程的变量 pthread_t myThread; res = pthread_create(&myThread, NULL, ThreadFun, NULL); if (res != 0) { printf("线程创建失败"); return 0; } //等待 myThread 线程执行完成,并用 thread_result 指针接收该线程的返回值 res = pthread_join(myThread, &thread_result); if (res != 0) { printf("等待线程失败"); } printf("%s", (char*)thread_result); return 0; }假设程序存储在 thread.c 文件中,执行过程如下:
[root@localhost ~]# gcc thread.c -o thread.exe -lpthread
[root@localhost ~]# ./thread.exe
http://c.biancheng.net
return "http://c.biancheng.net";重新编译、执行此程序,会发现程序的执行结果和之前完全相同。这意味着当线程执行结束时,无论是采用 return 语句还是调用 pthread_exit() 函数,主线程中的 pthread_join() 函数都可以接收到线程的返回值。
#include <stdio.h> #include <pthread.h> void *ThreadFun(void *arg) { sleep(5);//等待一段时间 printf("http://c.biancheng.net\n"); } int main() { int res; pthread_t myThread; res = pthread_create(&myThread, NULL, ThreadFun, NULL); if (res != 0) { printf("线程创建失败"); return 0; } printf("C语言中文网\n"); return 0; }编译、执行此程序,输出结果为:
C语言中文网
通过执行结果可以看到,主线程正常执行结束,myThread 线程并没有输出指定的数据。原因很简单,主线程执行速度很快,主线程最后执行的 return 语句不仅会终止主线程执行,还会终止其它子线程执行。也就是说,myThread 线程还没有执行输出语句就被终止了。return 0;
用如下语句替换:
pthread_exit(NULL);重新编译、执行程序,运行结果为:
C语言中文网
http://c.biancheng.net
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有