pthread_exit()函数:
#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;
}
pthread_exit() 和 return 的区别
#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 线程还没有执行输出语句就被终止了
将main函数的最后一句换成 pthread_exit(NULL);
输出为:
C语言中文网
http://c.biancheng.net
两个都能结束线程,但是pthread_exit() 只用于线程,return可以用于函数等返回,并且pthread_exit() 函数只会终止当前线程,不会影响进程中其它线程的执行。
学习内容:
提示:这里可以添加要学的内容
例如:
- 搭建 Java 开发环境
- 掌握 Java 基本语法
- 掌握条件语句
- 掌握循环语句