Is errno
on MSVC thread-safe?
According to the answers in this question POSIX requires that errno
is thread-safe. But MSVC is probably not POSIX compliant and MSDN does not tell anything about thread-safety. MSDN contradictory mentions that errno
is declared as extern int errno;
, but also as #define errno (*_errno())
errno is thread-safe. Each thread has its own errno stored in a __user_perthread_libspace block. This means that each thread can call errno -setting functions independently and then check errno afterwards without interference from other threads.
It's safe to read and write to one instance of a type even if another thread is reading or writing to a different instance of the same type. For example, given objects A and B of the same type, it's safe when A is being written in thread 1 and B is being read in thread 2.
Generally, yes. If every thread/path that modifies or reads the list locks the same mutex before doing so, then access to the list can be considered thread safe. Note that caveats apply if someone holds on to iterators, references or pointers to list items outside the scope of the lock.
If a single thread calling read never processes the same data twice, then read is thread safe if two threads calling it also never process the same data twice.
Although MSVC is definitely not POSIX compliant, errno
is implemented in the MSVC runtime (at least as of MSVC2008) in a threadsafe manner.
Although the documentation states that it is extern int errno
it's actually implemented as a #define
to a function which allows thread-safety to be imposed. If you step through this function in the disassembly window, it is clear that thread local storage is used.
Sadly I can't point to any official documentation that confirms this but such is life!
I can't find anywhere on the MSDN site where this is discussed. However, many functions which returns static buffers are already thread safe in MSVC (i.e. they return pointers to thread local buffers). So it'd be surprising if errno wasn't thread safe.
The MSVC header files all have this definition:
#ifndef _CRT_ERRNO_DEFINED
#define _CRT_ERRNO_DEFINED
_CRTIMP extern int * __cdecl _errno(void);
#define errno (*_errno())
errno_t __cdecl _set_errno(_In_ int _Value);
errno_t __cdecl _get_errno(_Out_ int * _Value);
#endif /* _CRT_ERRNO_DEFINED */
And a small test program showd that 2 threads setting errno did at least not affect eachother. So I'd say it's safe to assume errno is thread safe (though probably not if you link to the single thread CRT)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With