Thread-local storage

Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread.
While the use of global variables is generally discouraged in modern programming, legacy operating systems such as UNIX are designed for uniprocessor hardware and require some additional mechanism to retain the semantics of pre-reentrant APIs. An example of such situations is where functions use a global variable to set an error condition (for example the global variable codice_1 used by many functions of the C library). If codice_1 were a global variable, a call of a system function on one thread may overwrite the value previously set by a call of a system function on a different thread, possibly before following code on that different thread could check for the error condition. The solution is to have codice_1 be a variable that looks like it is global, but in fact exists once per thread—i.e., it lives in thread-local storage. A second use case would be multiple threads accumulating information into a global variable. To avoid a race condition, every access to this global variable would have to be protected by a mutex. Alternatively, each thread might accumulate into a thread-local variable (that, by definition, cannot be read from or written to from other threads, implying that there can be no race conditions). Threads then only have to synchronise a final accumulation from their own thread-local variable into a single, truly global variable.
Many systems impose restrictions on the size of the thread-local memory block, in fact often rather tight limits. On the other hand, if a system can provide at least a memory address (pointer) sized variable thread-local, then this allows the use of arbitrarily sized memory blocks in a thread-local manner, by allocating such a memory block dynamically and storing the memory address of that block in the thread-local variable. On RISC machines, the calling convention often reserves a thread pointer register for this use.
Windows implementation.
The application programming interface (API) function codice_4 can be used to obtain an unused "TLS slot index"; the "TLS slot index" will then be considered 'used'.
The codice_5 and codice_6 functions are then used to read and write a memory address to a thread-local variable identified by the "TLS slot index". codice_6 only affects the variable for the current thread. The codice_8 function can be called to release the "TLS slot index".
There is a Win32 Thread Information Block for each thread. One of the entries in this block is the thread-local storage table for that thread.
TlsAlloc returns an index to this table, unique per address space, for each call. Each thread has its own copy of the thread-local storage table. Hence, each thread can independently use TlsSetValue(index) and obtain the specified value via TlsGetValue(index), because these set and look up an entry in the thread's own table.
Apart from TlsXxx function family, Windows executables can define a section which is mapped to a different page for each thread of the executing process. Unlike TlsXxx values, these pages can contain arbitrary and valid addresses. These addresses, however, are different for each executing thread and therefore should not be passed to asynchronous functions (which may execute in a different thread) or otherwise passed to code which assume that a virtual address is unique within the whole process. TLS sections are managed using memory paging and its size is quantized to a page size (4kB on x86 machines).
Such sections may only be defined inside a main executable of a program - DLLs should not contain such sections, because they are not correctly initialized when loading with LoadLibrary.
Pthreads implementation.
In the Pthreads API, memory local to a thread is designated with the term Thread-specific data.
The functions codice_9 and codice_10 are used respectively to create and delete a key for thread-specific data. The type of the key is explicitly left opaque and is referred to as codice_11. This key can be seen by all threads. In each thread, the key can be associated with thread-specific data via codice_12. The data can later be retrieved using codice_13.
In addition codice_9 can optionally accept a destructor function that will automatically be called at thread exit, if the thread-specific data is not "NULL". The destructor receives the value associated with the key as parameter so it can perform cleanup actions (close connections, free memory, etc.). Even when a destructor is specified, the program must still call codice_10 to free the thread-specific data at process level (the destructor only frees the data local to the thread).
Language-specific implementation.
Apart from relying on programmers to call the appropriate API functions, it is also possible to extend the programming language to support thread local storage (TLS).
C and C++.
In C11, the keyword codice_16 is used to define thread-local variables. The header codice_17, if supported, defines codice_18 as a synonym for that keyword. Example usage:
thread_local int foo = 0;
C++11 introduces the codice_18 keyword which can be used in the following cases
Aside from that, various compiler implementations provide specific ways to declare thread-local variables:
On Windows versions before Vista and Server 2008, codice_23 works in DLLs only when those DLLs are bound to the executable, and will "not" work for those loaded with "LoadLibrary()" (a protection fault or data corruption may occur).
Common Lisp (and maybe other dialects).
Common Lisp provides a feature called dynamically scoped variables.
Dynamic variables have a binding which is private to the invocation of a function and all of the children called by that function.
This abstraction naturally maps to thread-specific storage, and Lisp implementations that provide threads do this. Common Lisp has numerous standard dynamic variables, and so threads cannot be sensibly added to an implementation of the language without these variables having thread-local semantics in dynamic binding.
For instance the standard variable codice_24 determines the default radix in which integers are printed. If this variable is overridden, then all enclosing code will print integers in an alternate radix:
If functions can execute concurrently on different threads, this binding has to be properly thread-local, otherwise each thread will fight over who controls a global printing radix.
D.
In D version 2, all static and global variables are thread-local by default and are declared with syntax similar to "normal" global and static variables in other languages. Global variables must be explicitly requested using the "shared" keyword:
int threadLocal; // This is a thread-local variable.
shared int global; // This is a global variable shared with all threads.
The "shared" keyword works both as the storage class, and as a type qualifier – "shared" variables are subject to some restrictions which statically enforce data integrity. To declare a "classic" global variable without these restrictions, the unsafe "__gshared" keyword must be used:
__gshared int global; // This is a plain old global variable.
Java.
In Java, thread-local variables are implemented by the class object. ThreadLocal holds variable of type T, which is accessible via get/set methods. For example, ThreadLocal variable holding Integer value looks like this:
private static final ThreadLocal<Integer> myThreadLocalInteger = new ThreadLocal<Integer>();
At least for Oracle/OpenJDK, this does not use native thread-local storage in spite of OS threads being used for other aspects of Java threading. Instead, each Thread object stores a (non-thread-safe) map of ThreadLocal objects to their values (as opposed to each ThreadLocal having a map of Thread objects to values and incurring a performance overhead).
.NET languages: C# and others.
In .NET Framework languages such as C#, static fields can be marked with the
ThreadStatic attribute:
class FooBar
 [ThreadStatic]
 private static int _foo;
In .NET 4.0 the System.Threading.ThreadLocal<T> class is available for allocating and lazily loading thread-local variables.
class FooBar
 private static System.Threading.ThreadLocal<int> _foo;
Also an API
is available for dynamically allocating thread-local variables.
Object Pascal.
In Object Pascal (Delphi) or Free Pascal the "threadvar" reserved keyword can be used instead of 'var' to declare variables using the thread-local storage.
var
 mydata_process: integer;
threadvar
 mydata_threadlocal: integer;
Objective-C.
In Cocoa, GNUstep, and OpenStep, each NSThread object has a thread-local dictionary that can be accessed through the thread's threadDictionary method.
NSMutableDictionary *dict = [[NSThread currentThread] threadDictionary];
dict[@"A key"] = @"Some data";
Perl.
In [[Perl]] threads were added late in the evolution of the language, after a large body of extant code was already present on the [[Comprehensive Perl Archive Network]] (CPAN). Thus, threads in Perl by default take their own local storage for all variables, to minimise the impact of threads on extant non-thread-aware code. In Perl, a thread-shared variable can be created using an attribute:
use threads;
use threads::shared;
my $localvar;
my $sharedvar :shared;
PureBasic.
In [[PureBasic]] thread variables are declared with the keyword Threaded.
Threaded Var
Python.
In [[Python (programming language)|Python]] version 2.4 or later, "local" class in "threading" module can be used to create thread-local storage.
import threading
mydata = threading.local()
mydata.x = 1
Ruby.
[[Ruby (programming language)|Ruby]] can create/access thread-local variables using []=/[] methods:
Thread.current[:user_id] = 1
Rust.
Thread-local variables can be created in [[Rust (programming language)|Rust]] using the macro provided by the Rust standard library:
use std::cell::RefCell;
use std::thread;
thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
FOO.with(|f| {
 assert_eq!(*f.borrow(), 1);
 *f.borrow_mut() = 2;
// each thread starts out with the initial value of 1, even though this thread already changed its copy of the thread local value to 2
let t = thread::spawn(move|| {
 FOO.with(|f| {
 assert_eq!(*f.borrow(), 1);
 *f.borrow_mut() = 3;
});
// wait for the thread to complete and bail out on panic
t.join().unwrap();
// original thread retains the original value of 2 despite the child thread changing the value to 3 for that thread
FOO.with(|f| {
 assert_eq!(*f.borrow(), 2);
External links.
[[Category:Threads (computing)]]
[[Category:Variable (computer science)]]
[[Category:Software design patterns]]