乱七八糟的学习记录

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() 函数只会终止当前线程,不会影响进程中其它线程的执行。


学习内容:

提示:这里可以添加要学的内容

例如:

  1. 搭建 Java 开发环境
  2. 掌握 Java 基本语法
  3. 掌握条件语句
  4. 掌握循环语句
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值