How does thread_local! macro work?

ok, thread_local is a macro that implements LocalKey, but, whats it???

LocalKey doc says:

This key uses the fastest possible implementation available to it for the target platform.

So which platform are you interested in?

Conceptually you can think of each thread local variable as a map from thread ID to whatever data you supply, that can be accessed for the current thread ID only. However, the implementation on each platform will normally be much more efficient than a map per variable. And normally no locking is needed.

1 Like

can u explain me using the linux platform??

On Linux it would use the TLS support of the ELF ABI. Basically you have a .tdata section whose content gets copied into the thread local storage area for each thread and then when trying to access the TLS, you call __tls_get_addr with the id of the current DSO (an executable or shared library) and the offset of the TLS variable in the .tdata section and this returns the address of the TLS variable for the current thread. Most architectures also have a platform specific sequence of instructions which the linker can "relax" an __tls_get_addr call to by directly accessing the register containing thw address of the thead local storage area (eg %fs on x86). This is faster, but can only be done when specific conditions are met like when linking an executable.

2 Likes