kai
kai

Reputation: 1211

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

Upvotes: 2

Views: 351

Answers (2)

vdbuilder
vdbuilder

Reputation: 12984

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

Upvotes: 1

Duck
Duck

Reputation: 27562

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.

Upvotes: 9

Related Questions