c - 当我们可以使用 return 时,为什么我们使用 pthread_exit()?

标签 c unix

在以下程序中 return p给出与 pthread_exit(p) 相同的输出.那为什么要用pthread_exit() ?

void *foo(void *p){
    *((int *)p) += 1;
    pthread_exit(p);

}

int main()
{
    pthread_t t;
    int i=9;
    int *j;
    pthread_create(&t,NULL, foo, &i);
    pthread_join(t,(void**)&j);
    printf("%d\n",*j);
}

最佳答案

pthread_exit()线程是什么exit()用于主程序。

你能不能总是使用 return 来终止主程序? ?
我猜不是。这就是为什么exit()pthread_exit()存在。

从线程的主函数返回执行对 pthread_exit() 的隐式调用。 .无论您如何终止线程,都会调用该函数。它负责线程的清理。

但是如果函数 foo()调用函数 bar()bar()决定它必须终止线程,调用 pthread_exit() 更方便比从bar()返回并检查 foo() 中的返回值.与return的烦恼当链中调用的数量增加时会增加。

关于c - 当我们可以使用 return 时,为什么我们使用 pthread_exit()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36382444/

相关文章:

c++ - c++ matlab代码上的奇怪错误

c - 执行另一个程序 + child 死亡

c - Linux 中 C 中的递归文件删除

有人可以解释在 Pebble C Watchface 教程中找到的部分代码吗?

c - C语言中函数的返回值是字符串

c - ALSA hw_params 缓冲区大小是物理卡内存大小吗?

linux - 如何将文件复制到时间戳自动生成的文件夹?

c - 仅删除用户输入,而不是整个屏幕

c - 在进程之间同步消息队列

bash - 如何使用 sed 或 awk 在文件的特定行插入特定字符?