我正在检查“pthread_join”的行为并具有以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>

#include <pthread.h>

void *thread(void *vargp)
{
    pthread_detach(pthread_self());
    pthread_exit((void *)42);
}

int main()
{
    int i = 1;
    pthread_t tid;

    pthread_create(&tid, NULL, thread, NULL);

    sleep(1);
    pthread_join(tid, (void **)&i);
    printf("%d\n", i);
    printf("%d\n", errno);
}

在我的平台上观察到的输出(Linux 3.2.0-32-generic#51-Ubuntu SMP x86_64 GNU/Linux):

带有 'sleep(1)' 的
  • 注释掉了:
    42
    0
  • 与 sleep 语句,它产生:
    1
    0

  • 根据 pthread_join 的手册页,当我们尝试加入不可连接的线程时,我们应该得到错误“ EINVAL ”,但是,上述两种情况都没有设置 errno。而且在第一种情况下,似乎我们甚至可以获得分离线程的退出状态,我对结果感到困惑。有人能解释一下吗?谢谢

    [编辑]: 我意识到第一个 printf 可能会重置 'errno',但是,即使在我交换了两个 'printf' 语句的顺序之后,我仍然得到相同的结果。

    最佳答案

    你的期望是错误的。在分离的线程上调用 pthread_join 会调用未定义的行为。不需要设置 errno ,返回错误代码,甚至根本不返回。

    如果您需要引用,



    资料来源:http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html

    另请注意,大多数 pthread 函数(包括 pthread_join )不使用 errno 。相反,它们将错误代码作为返回值返回。因此,即使在调用 pthread 函数时没有调用未定义的行为,在调用 pthread 函数后检查 errno 也是错误的。

    关于c - pthread : join a detached thread doesn't set errno correctly,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13917944/

    10-11 23:19
    查看更多