Is errno thread-safe?

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

See 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.

Also see 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.

Leave a Comment