Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread local storage

Tags:

c#

.net

what is the best way to store some variable local to each thread?

like image 631
user496949 Avatar asked Nov 16 '10 02:11

user496949


People also ask

What is thread-local storage used for?

Thread Local Storage (TLS) is the mechanism by which each thread in a given multithreaded process allocates storage for thread-specific data. In standard multithreaded programs, data is shared among all threads of a given process, whereas thread local storage is the mechanism for allocating per-thread data.

What is thread-local storage 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 runtime 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 difference between thread-local storage and static data?

In some ways, TLS is similar to static data. The only difference is that TLS data are unique to each thread. Most thread libraries-including Windows and Pthreads-provide some form of support for thread-local storage; Java provides support as well.

Is thread-local storage fast?

Yes, you are correct that TLS can be as fast as a pointer lookup. It can even be faster on systems with a memory management unit.


1 Answers

If you use .Net 4.0 or above, as far as I know, the recommended way is to use System.Threading.ThreadLocal<T> which also gives lazy initialization as a bonus.

like image 67
Ali Ferhat Avatar answered Oct 01 '22 07:10

Ali Ferhat