Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread local variables and fs segment

I am reading from a thread local variable in my code like this,

// tid_local is declared as __thread int tid_local;
long tid = tid_local

Looking around the dissassembled code, I saw something like this, which I suspect is the instruction which assigns tid by reading tid_local.

movslq %fs:0xfffffffffffffffc,%rbx

Now my question is if this can really be the instruction which is doing this, that is, reading from the local thread variable and if gcc always uses the fs segment for storing thread local variables. How is this supposed to work?

like image 477
MetallicPriest Avatar asked Jan 05 '12 17:01

MetallicPriest


People also ask

What is TLS segment?

TLS Segment: This is the image of data in each module and specified by the PT_TLS program header in each module. Not every module has a PT_TLS program header and thus not every module has a TLS segment. Each module has at most one TLS segment and correspondingly at most one PT_TLS program header.

How does thread local storage work?

With thread local storage (TLS), you can provide unique data for each thread that the process can access using a global index. One thread allocates the index, which can be used by the other threads to retrieve the unique data associated with the index.

What is ThreadLocal variable in C?

Thread-local storage (TLS) is a mechanism by which variables are allocated such that there is one instance of the variable per extant thread. The run-time model GCC uses to implement this originates in the IA-64 processor-specific ABI, but has since been migrated to other processors as well.

What is ThreadLocal state?

ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID). For example, the class below generates unique identifiers local to each thread. A thread's id is assigned the first time it invokes ThreadId.


1 Answers

Yes, this could well be the right instruction. From the gcc manual:

-mtls-direct-seg-refs

-mno-tls-direct-seg-refs

Controls whether TLS variables may be accessed with offsets from the TLS segment register (%gs for 32-bit, %fs for 64-bit), or whether the thread base pointer must be added. Whether or not this is legal depends on the operating system, and whether it maps the segment to cover the entire TLS area.

edit Here is an excellent link suggested by @janneb in the comments: http://www.akkadia.org/drepper/tls.pdf

like image 197
NPE Avatar answered Nov 01 '22 14:11

NPE