c - errno 是线程安全的吗?

标签 c linux multithreading gcc

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.

关于c - errno 是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1694164/

相关文章:

c - MPI_Gatherv 无法正常工作

c - 如何将指针变为指针到指针?

linux - Windows 7共享ubuntu目录但看不到里面的文件怎么办?

c++ - 为什么我的计算机中 long int 和 int 具有相同的最大值

检查线程结束条件

linux - 如何使用 awk 工具对齐 csv 文件中的列

java - 无法在 Runnable 中实现 run()

java - 为什么这个多线程程序的执行时间如此奇怪?

java - 让线程相互等待。

c - 有没有一种可靠的方法可以知道哪些库可以在 elf 二进制文件中 dlopen()ed?