Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSVC errno thread safety

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

like image 603
Juraj Blaho Avatar asked Jun 20 '11 14:06

Juraj Blaho


People also ask

Is errno thread safe?

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.

How to ensure thread safety in c++?

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.

Is c++ list thread safe?

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.

Is read thread safe?

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.


2 Answers

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!

like image 166
David Heffernan Avatar answered Sep 19 '22 08:09

David Heffernan


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)

like image 22
nos Avatar answered Sep 22 '22 08:09

nos