Thread-local storage

Thread-local storage

Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread.

This is sometimes needed because all threads in a process share the same address space.In other words, data in a static or global variable is normally always located at the same memory location, when referred to by threads from the same process.
Variables on the stack however are local to threads, because each thread has its own stack, residing in a different memory location.

Sometimes it is desirable that two threads referring to the same static or global variable are actually referring to different memory locations, thereby making the variable thread local, a canonical example being the C error code variable errno.

If it is possible to make at least a memory address sized variable thread local, it is in principle possible to make arbitrarily sized memory blocks thread local, by allocating such a memory block and storing the memory address of that block in a thread local variable.

Windows implementation

The API function TlsAlloc can be used to obtain an unused "TLS slot index"; the "TLS slot index" will then be considered ‘used’.

The TlsGetValue and TlsSetValue functions can then be used to read and write a memory address to a thread local variable identified by the "TLS slot index". TlsSetValue can only affect the variable for the current thread.

The TlsFree function can be called to release the "TLS slot index"; the index will then be considered ‘unused’ and a new call to TlsAlloc can return it again.

Pthreads implementation

TLS with Pthreads ("Thread-Specific Data" in Pthreads nomenclature) is similar to TlsAlloc and related functionality for Windows. pthread_key_create creates a "key", with an optional "destructor", that can later be associated with thread specific data via pthread_setspecific. The data can be retrieved using pthread_getspecific. If the thread specific value is not "NULL", the "destructor" will be called when the thread exits. Additionally, "key" must be destroyed with pthread_key_delete.

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 TLS.

Java

In Java thread local variables are implemented by the Javadoc:SE|java/lang|ThreadLocal class. A ThreadLocal object maintains a separate instance of the variable for each thread that calls the object's get or set method. The following example (for J2SE 5.0 or later version of Java) illustrates using a ThreadLocal that holds an Integer object:

ThreadLocal local = new ThreadLocal(){ @Override protected Integer initialValue(){ return 1; } };

the preceding code declares and instantiates a ThreadLocal object local which returns an initial value of 1 if no other value has been stored for the calling thread. The following code increments the value for the currently executing thread.

local.set( local.get()+1 );

local.get() returns the current Integer object associated with the current thread, or 1 if no object has yet been associated with the thread. The code calls local.set() to set a new value associated with the thread. (Note that the above example uses both generics and autoboxing—features added to Java in J2SE 5.0.)

Sun Studio C/C++, IBM XL C/C++, GNU C & Intel C/C++(Linux systems)

The keyword __thread is used like this: __thread int number;
*__thread defines "number" to be a thread local variable.
*int defines the type of "number" to be of type int.

Visual C++, Intel C/C++(Windows systems)

In Visual C++ the keywords declspec(thread) are used like this: __declspec(thread) int number;
*__declspec(thread) defines "number" to be a thread local variable.
*int defines the type of "number" to be of type int.
* On operating systems prior to Vista and Server 2008 __declspec(thread) works in DLLs only when those DLLs are bound to the executable, and will "not" work for those loaded with LoadLibrary() (a protection fault will occur)
* There are additional rules: [http://msdn2.microsoft.com/en-us/library/2s9wt68x.aspx "Rules and Limitations for TLS"] in MSDN.

Borland C++ Builder

In Borland C++ Builder the keywords __declspec(thread) are used like this: __declspec(thread) int number;the same in a more elegant way: int __thread number;
*__declspec(thread) defines "number" to be a thread local variable. __thread is a synonym for __declspec(thread).
*int defines the type of "number" to be of type int.

GCC

GCC implements __thread as above.

The initialiser must be a compile-time constant, even in C++. E.g. __thread int number = 1;but not void f(int number) { static __thread int number_copy = number;or (C++) __thread int number = calculate_number();

C# and other .NET languages

Static fields can be marked with [http://msdn2.microsoft.com/en-us/library/system.threadstaticattribute(vs.80).aspx ThreadStaticAttribute] :

class FooBar { [ThreadStatic] static int foo; }

Also [http://msdn2.microsoft.com/en-us/library/system.threading.thread.getnameddataslot(vs.80).aspx an API] is available for dynamically allocating thread local variables.

Python

In 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

Delphi

In Delphi you can use the 'threadvar' reserved keyword instead of 'var' to declare variables using the thread-local storage.

var mydata_process: integer; threadvar mydata_threadlocal: integer;

External links

* [http://people.redhat.com/drepper/tls.pdf ELF Handling For Thread-Local Storage] — Document about an implementation in C or C++.
* [http://www.dre.vanderbilt.edu/Doxygen/Stable/ace/classACE__TSS.html#_details ACE_TSS< TYPE > Class Template Reference]
* [http://www.roguewave.com/support/docs/hppdocs/thrref/rwtthreadlocal.html#sec4 RWTThreadLocal Class Template Documentation]
*Article " [http://www.c-sharpcorner.com/Code/2003/March/UseThreadLocals.asp Use Thread Local Storage to Pass Thread Specific Data] " by Doug Doedens
*" [http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1966.html Thread-Local Storage] " by Lawrence Crowl
*" [http://www.asyncop.net/Link.aspx?TLS Developer's Reference]


Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать курсовую

Look at other dictionaries:

  • Thread Local Storage — Le Thread Local Storage (TLS), ou mémoire locale de thread, est un type de mémoire spécifique et locale à un thread. Ce mécanisme est parfois requis parce que tous les threads d un même processus partagent le même espace d adressage. Donc, les… …   Wikipédia en Français

  • Thread safety — is a computer programming concept applicable in the context of multi threaded programs. A piece of code is thread safe if it functions correctly during simultaneous execution by multiple threads. In particular, it must satisfy the need for… …   Wikipedia

  • Thread (informatique) — Pour les articles homonymes, voir Thread et Fil. Un processus avec deux threads. Un thread ou fil (d exécution) o …   Wikipédia en Français

  • Thread (Informatik) — Ein Thread (auch: Aktivitätsträger oder leichtgewichtiger Prozess) bezeichnet in der Informatik einen Ausführungsstrang oder eine Ausführungsreihenfolge in der Abarbeitung eines Programms. Ein Thread ist Teil eines Prozesses. Man unterscheidet… …   Deutsch Wikipedia

  • Thread (computer science) — This article is about the concurrency concept. For the multithreading in hardware, see Multithreading (computer architecture). For the form of code consisting entirely of subroutine calls, see Threaded code. For other uses, see Thread… …   Wikipedia

  • Win32 Thread Information Block — Esta página o sección está siendo traducida del idioma inglés a partir del artículo Win32 Thread Information Block, razón por la cual puede haber lagunas de contenidos, errores sintácticos o escritos sin traducir. Puedes colaborar con… …   Wikipedia Español

  • Win32 Thread Information Block — In computing, the Win32 Thread Information Block (TIB) is a data structure in Win32 on x86 that stores info about the currently running thread.The TIB is officially undocumented for Windows 9x. The Windows NT series DDK includes a struct NT TIB… …   Wikipedia

  • Kernel Thread — Ein Thread (auch: Aktivitätsträger oder leichtgewichtiger Prozess, vereinzelt auch: Faden) bezeichnet in der Informatik einen Ausführungsstrang oder eine Ausführungsreihenfolge in der Abarbeitung eines Programms. Ein Thread ist Teil eines… …   Deutsch Wikipedia

  • C++11 — C++11, also formerly known as C++0x,[1] is the name of the most recent iteration of the C++ programming language, replacing C++TR1, approved by the ISO as of 12 August 2011.[2] The name is derived from the tradition of naming language versions by …   Wikipedia

  • C++0x — is the planned new standard for the C++ programming language. It is intended to replace the existing C++ standard, ISO/IEC 14882, which was published in 1998 and updated in 2003. These predecessors are informally known as C++98 and C++03. The new …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”