iam1708 via DotNetMonster.com said:
I was looking at the docs for Thread and can't understand the different
between "unnamed data slot "and "data slot".and docs in Thread.GetData()
say "Threads use a local store memory mechanism to store thread-specific
data." what is "thread-specific data"?
Best regards
wmt
email:
[email protected]
Hi
What you have read about is a Thread Local Storage (TLS). A TLS
variable is a variable that all the threads access in the same way,
but each of the thread can store a different value (each thread has
different copy). TLS makes it easy to write thread safe code. Each
thread has its own stack which means that the variables that declared
on the stack are not shared, but object and class member variables are
shared among all threads. Using TLS you can create non shared
non-stack based variables. In the days of Win32 when I was teaching
the TLS subject I used to give the C strtok() function example: The
function knows how to split a string by tokens. At first you call it
with two arguments, the token string and the start address of the
source string. To get the next word, you call it again, but now you
pass NULL as the address. The function remembers the last address in a
static variable. When you try to split two or more strings with two or
more threads concurrently, you find that all threads work on the same
(last) string. This happens because of the shared nature of the static
variable. Making this variable a TLS solves the problem. Each thread
gets its own copy of the last address state. In .Net there are three
ways to have a TLS:
1) An unnamed TLS, Using Thread.AllocateDataSlot(); the result (slot)
of this method should be shared among all thread. Each thread that
need a private storage uses the Thread.SetData() and Thread.GetData()
passing it the shared slot.
2) A named TLS, Using AllocateNamedDataSlot("Name") to create the
slot. Each thread uses the GetNamedDataSlot() to get the slot and then
the Thread.SetData() and Thread.GetData() to work with the slot.
3) The [ThreadStaticAttribute], on a static variable.
The third option is the easiest one, you just decorate a class
variable and you get a TLS. The second is easier than the first
because you don't have to share a common slot between threads, but you
may collide with other code that uses the same name, so be careful.
If you need a TLS for a single class code, use the
ThreadStaticAttribute. If you need the TLS in many places (many
classes) use one of the Slot based methods. You may also consider the
call context mechanism, if you need the TLS state per call along the
call path.
You may also consider using an object instance per thread which omits
the need of TLS.
Alon Fliess
CTO
The Sela Group