c - errno 是线程安全的吗?

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

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

最佳答案

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

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

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.

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):

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 is thread-local; setting it in one thread does not affect its value in any other thread.

https://stackoverflow.com/questions/1694164/

相关文章:

python - 将数字四舍五入到最接近的整数

python - 是否可以在列表理解中使用 'else' ?

python - 如何查找我的系统中安装了哪个版本的 TensorFlow?

linux - 如何找出目录或文件所在的挂载/分区? (Linux 服务器)

python - 如何在 Python 3.x 和 Python 2.x 中使用 pip

linux - 如何杀死僵尸进程

linux - 如何在 Linux 上将所有文件夹和文件重命名为小写?

python - 为什么打印到标准输出这么慢?可以提速吗?

python - 如何使 Python 脚本像 Linux 中的服务或守护程序一样运行

python - 何时使用 Tornado,何时使用 Twisted/Cyclone/GEvent/