Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This code is not thread-safe, isn't it?

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...

like image 836
kai Avatar asked Feb 03 '26 12:02

kai


2 Answers

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.

like image 76
Duck Avatar answered Feb 06 '26 04:02

Duck


The code is only using errno in one thread, in fact the code only shows one thread. So, this snippet is thread safe.

like image 31
vdbuilder Avatar answered Feb 06 '26 02:02

vdbuilder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!