MSVC errno thread safety

前端 未结 2 1393
Happy的楠姐
Happy的楠姐 2021-01-04 14:26

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

相关标签:
2条回答
  • 2021-01-04 14:51

    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!

    0 讨论(0)
  • 2021-01-04 15:06

    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)

    0 讨论(0)
提交回复
热议问题