We help IT Professionals succeed at work.

errno and multithreading

msilbers asked
Dear all,
I'd like to know, how to make errno global variable thread-safe ( the one , system calls return error codes through) . Suppose, I have two threads, and both of them call write(). It fails on both either, but for one errno is EINVAL and for the second ENODEV. I guess that if this happens more or less in the same time, I would get only the last error code.
Does anyone have any idea how to make this errno thread safe, and what might be a workaround ?
Watch Question

You don't need to worry about that.  errno is defined as global to each thread (meaning each thread automatically gets it's own errno instance, so it is thread-safe).  If there is a failure in one thread, it will not change the value of errno in another thread, unless the thread library you are using in not posix compliant.
One thing to keep in mind is that some of the functions associated with errno, such as strerror, are not thread safe.  Strerror is not thread-safe beacuse it uses a statically allocated buffer for the error message.  In these cases, you can usually find an implementation of the funtion that is thread safe.  In the case of strerror, the function is strerror_r that takes extra arguments such as your own allocated buffer, and the size of your buffer.


Thanks a lot!
but I want to understand, how it is implemented, I mean as global per thread and not per process. The variable is defined as extern in <errno.h> so you get the instance per process, that is,  it is a global you may refer to in the program code. So, given that threads have shared memory of the process, how can you enforce some unusual behaviour, that is - separate the copies of the global variable for each thread? I would really appreciate the answer


Great technical answer, but could not answer how it works
Sorry, I have not had much time to go digging through the source, but I can tell you that errno is defined as a volatile int.  I am still curious myself.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.