Home > database >  What is the mechanism to address errno when calling same function from different threads
What is the mechanism to address errno when calling same function from different threads

Time:03-06

Imagine main() creates two threads. Each thread gets it errno (as a private function). There's a function in the program, which can be called by both of these two threads. It is made thread safe.

How compiler will arrange this function to ensure its same code calls appropriate errno function? How "thread environment" is being passed to the same piece of code?

Edit. The question is not about errno per se. Question is about how this common function knows which errno to call when it gets execution. From where the same piece of code gets different thread-specific info on errno function?

Edit: does it assume that if I pass 3 variables to the function, there're actually several more variables passed behind the scenes, and one of them is this FS processor register, which points to thread environment? If I used say errno in this common function, how this function knows that it must search for errno in its environment - is this mechanism embedded in errno definition?

Conclusion: due to declaration of errno as __thread compiler knows that this entity (variable or whatever) is thread-specific, and to access this compiler uses another "background" input to the function - for example, processor's FS register which always contains pointer to thread environment.

CodePudding user response:

errno is thread-local, meaning that it has a separate value maintained per-thread, in an implementation-dependent manner.

On my environment, it happens to be defined (macro) as *__errno_location (), where __errno_location() "shall return the address of the errno variable for the current thread." (ref).

Under the hood, this uses the __thread specifier in at least one case, but it can use any suitable mechanism for thread-local storage such as special support from the threading library/operating system.

On x86_64 Linux thread-local information can be reached through the fs register which points to thread-local data; on x86_64 Windows the gs register points to the Windows NT TIB which does the same. Here's a Linux example showing the generated code: https://godbolt.org/z/YeqEvdhnc

CodePudding user response:

From the C Standard (7.5 Errors <errno.h>)

errno

which expands to a modifiable lvalue201) that has type int and thread local storage duration,

So each thread has its own errno.

The so-called common function is called in the thread environment where it is called.

  • Related