linux - pthread_exit 返回值

标签 linux multithreading pthreads pthread-join

这让我很惊讶。

static int ret = 50;
void * thread_func(void *arg)
{
    pthread_exit(&ret);
}

int main(void)
{
    pthread_t thr;
    int *exit_status;
    pthread_create(&thr, NULL, thread_func, NULL);
    sleep(2);
    pthread_join(thr, (void **)&exit_status);
    printf("value of exit status - %d\n", *exit_status);

    ret = 20;
    pthread_join(thr, (void **)&exit_status);
    printf("value of exit status - %d\n", *exit_status);
    return 0;
}

输出是

value of exit status - 50
value of exit status - 20

我期望 exit_status 两次都是线程的实际退出值(在我的例子中是 50)。相反,它只是返回我用于 pthread_exit 的全局变量的值。这不是错误吗?

最佳答案

:如果您想指定如何获取 ret当前值,您会返回什么。

A:ret的地址。

:你返回了什么?

A:`ret.

的地址

:那么当调用者取消引用它时会得到什么?

A:ret的当前值。

您可能需要 pthread_exit(ret); —— 返回 retvalue,以及调用 的代码中的相应更改>pthread_join

关于linux - pthread_exit 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25417820/

相关文章:

php - 从 php 脚本执行 linux 命令

javascript - 在 Linux CLI 中解释和执行任意 Javascript

c - Linux 上的一个简单的 C 程序

java - 在此类的对象上调用 start() 安全吗? Java 并发实践中的一个例子

linux - 使用带 -L 选项的查找

linux - 运行 cron 后 Bash 清空变量,但手动运行

具有多个客户端的 Java 即时通讯工具无法正常工作

c++ - 编译时 -pthread 标志的意义

c - 如何在 Windows 上设置 pthreads?

c++ - GCC 8.3 + Linux 上的 boost::thread_specific_ptr 的 Valgrind 错误