11

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

Community
  • 1
  • 1
Juraj Blaho
  • 13,301
  • 7
  • 50
  • 96

2 Answers2

14

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!

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
3

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)

nos
  • 223,662
  • 58
  • 417
  • 506