本文介绍了pthread:加入分离的线程未正确设置errno的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am checking the behavior of 'pthread_join' and have the following code:

#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-通用#51-Ubuntu SMP x86_64 GNU/Linux):

Observed output on my platform (Linux 3.2.0-32-generic #51-Ubuntu SMP x86_64 GNU/Linux):

  1. 带有'sleep(1)'的注释:420

  1. with the 'sleep(1)' commented out:420

带有sleep语句,它产生:1个0

with the sleep statement, it produces:10

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

according to the man page of pthread_join, we should get the error 'EINVAL' when we are trying to join a non-joinable thread, however, neither cases above got the errno set. And also in the first case, it seemed that we can even get the exit status of a detached thread, I am confused with the result. Could anyone explain this? Thanks

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

: I realized that the first printf may reset 'errno', however, even after I swapped the order of the two 'printf' statements, I still got the same results.

推荐答案

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

Your expectation is wrong. Calling pthread_join on a detached thread invokes undefined behavior. There is no requirement to set errno, return the error code, or even return at all.

如果您需要引用,

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

此外,请注意,大多数pthread函数(包括pthread_join)都不使用errno.相反,他们返回错误代码作为其返回值.这样,即使您在调用pthread函数时未调用未定义的行为,也要在检查它后检查errno是错误的.

Also, note that most pthread functions, including pthread_join, do not use errno. Instead they return the error code as their return value. As such, inspecting errno after calling a pthread function is wrong even if you didn't invoke undefined behavior when you called it.

这篇关于pthread:加入分离的线程未正确设置errno的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 23:36