I saw a piece of code like this and wondered whether this is thread-safe:
int savedErrno = errno;
//call some function that may modifies errno
if (errno == xxx)
foo();
errno = savedErrno;
I don't think this is thread-safe, am I correct?
But I saw people write code like this, so I am not sure...
Can any one help me clarify this, thanks...
Each thread has its own (thread specific) copy of errno so that looks like it should be safe.
From man (3) errno:
errno is defined by the ISO C standard to be a modifiable lvalue of type int, and must not be explicitly declared; errno may be a macro. errno is thread-local; setting it in one thread does not affect its value in any other thread.
The code is only using errno in one thread, in fact the code only shows one thread. So, this snippet is thread safe.
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