gcc: Thread-Local

1 
1 6.63 Thread-Local Storage
1 =========================
1 
1 Thread-local storage (TLS) is a mechanism by which variables are
1 allocated such that there is one instance of the variable per extant
1 thread.  The runtime model GCC uses to implement this originates in the
1 IA-64 processor-specific ABI, but has since been migrated to other
1 processors as well.  It requires significant support from the linker
1 ('ld'), dynamic linker ('ld.so'), and system libraries ('libc.so' and
1 'libpthread.so'), so it is not available everywhere.
1 
1  At the user level, the extension is visible with a new storage class
1 keyword: '__thread'.  For example:
1 
1      __thread int i;
1      extern __thread struct state s;
1      static __thread char *p;
1 
1  The '__thread' specifier may be used alone, with the 'extern' or
1 'static' specifiers, but with no other storage class specifier.  When
1 used with 'extern' or 'static', '__thread' must appear immediately after
1 the other storage class specifier.
1 
1  The '__thread' specifier may be applied to any global, file-scoped
1 static, function-scoped static, or static data member of a class.  It
1 may not be applied to block-scoped automatic or non-static data member.
1 
1  When the address-of operator is applied to a thread-local variable, it
1 is evaluated at run time and returns the address of the current thread's
1 instance of that variable.  An address so obtained may be used by any
1 thread.  When a thread terminates, any pointers to thread-local
1 variables in that thread become invalid.
1 
1  No static initialization may refer to the address of a thread-local
1 variable.
1 
1  In C++, if an initializer is present for a thread-local variable, it
1 must be a CONSTANT-EXPRESSION, as defined in 5.19.2 of the ANSI/ISO C++
1 standard.
1 
1  See ELF Handling For Thread-Local Storage
1 (https://www.akkadia.org/drepper/tls.pdf) for a detailed explanation of
1 the four thread-local storage addressing models, and how the runtime is
1 expected to function.
1 

Menu