errno 是线程安全的吗? [英] Is errno thread-safe?

查看:39
本文介绍了errno 是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

errno.h 中,这个变量被声明为 extern int errno; 所以我的问题是,检查 errno 值是否安全在多线程代码中调用或使用 perror() 之后.这是线程安全变量吗?如果没有,那么还有什么选择?

In errno.h, this variable is declared as extern int errno; so my question is, is it safe to check errno value after some calls or use perror() in multi-threaded code. Is this a thread safe variable? If not, then whats the alternative ?

我在 x86 架构上使用带有 gcc 的 linux.

I am using linux with gcc on x86 architecture.

推荐答案

是的,它是线程安全的.在 Linux 上,全局 errno 变量是线程特定的.POSIX 要求 errno 是线程安全的.

Yes, it is thread safe. On Linux, the global errno variable is thread-specific. POSIX requires that errno be threadsafe.

参见 http://www.unix.org/whitepapers/reentrant.html

在 POSIX.1 中,errno 被定义为外部全局变量.但是这个定义是不可接受的多线程环境,因为它使用可能导致不确定性结果.问题是两个或更多的线程可能会遇到错误,所有导致设置相同的 errno.在这种情况下,线程可能最终会在它之后检查 errno已经被另一个人更新了线程.

In POSIX.1, errno is defined as an external global variable. But this definition is unacceptable in a multithreaded environment, because its use can result in nondeterministic results. The problem is that two or more threads can encounter errors, all causing the same errno to be set. Under these circumstances, a thread might end up checking errno after it has already been updated by another thread.

为了规避由此产生的不确定性,POSIX.1c 重新定义errno 作为可以访问的服务每个线程的错误号如下(ISO/IEC 9945:1-1996, §2.4):

To circumvent the resulting nondeterminism, POSIX.1c redefines errno as a service that can access the per-thread error number as follows (ISO/IEC 9945:1-1996, §2.4):

某些函数可能会在访问的变量中提供错误编号通过符号 errno.符号errno 定义为包括header ,如指定的C 标准...对于每一个线程过程中,errno 的值不应受函数调用的影响或其他线程对 errno 的赋值.

Some functions may provide the error number in a variable accessed through the symbol errno. The symbol errno is defined by including the header , as specified by the C Standard ... For each thread of a process, the value of errno shall not be affected by function calls or assignments to errno by other threads.

另见http://linux.die.net/man/3/errno

errno 是线程本地的;在一个线程中设置它不会影响它在任何其他线程中的值.

errno is thread-local; setting it in one thread does not affect its value in any other thread.

这篇关于errno 是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆