我正在检查’pthread_join’的行为并拥有以下代码:
#include #include #include #include #include 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("%dn", i); printf("%dn", errno); }
在我的平台上观察到的输出(Linux 3.2.0-32-generic#51-Ubuntu SMP x86_64 GNU / Linux):
根据pthread_join的手册页,当我们尝试加入一个不可连接的线程时,我们应该得到错误’ EINVAL ‘,但是,上面两种情况都没有设置errno。 而且在第一种情况下,似乎我们甚至可以获得分离线程的退出状态,我对结果感到困惑。 谁能解释一下呢? 谢谢
[编辑]:我意识到第一个printf可能会重置’errno’,但是,即使我交换了两个’printf’语句的顺序后,我仍然得到了相同的结果。
你的期望是错误的。 在分离的线程上调用pthread_join
调用未定义的行为。 没有要求设置errno
,返回错误代码,甚至根本不返回。
如果你需要引用,
如果pthread_join()的thread参数指定的值未引用可连接线程,则行为未定义。
资料来源: http : //pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html
另请注意,大多数pthread函数(包括pthread_join
)都不使用errno
。 相反,他们将错误代码作为返回值返回。 因此,在调用pthread函数之后检查errno
是错误的,即使您在调用它时没有调用未定义的行为。
通过读取函数pthread_join
的返回值得到此错误,请尝试以下操作:
if (errno = pthread_join(tid,NULL)) { printf("An error ocurred: %i", errno); }
以上就是c/c++开发分享pthread:加入一个分离的线程没有正确设置errno相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/541834.html