A Tech Log

February 2, 2009

Thread Local Storage and .Net

Filed under: Development — adallow @ 9:48 am
Tags: ,

the below is taken from:

http://www.developerfusion.com/article/4272/net-threading-part-ii/3/

The Thread class and System. Threading namespace also contain some methods and classes for realizing thread local storage. Thread local storage is a manner of storing data in a container that is unique to the thread. Many threads could then use the same named container to store their data without concern of collision. Each thread’s local storage is distinct from another thread’s local storage and is only available in the one thread. Listing 3 shows a small sample using the thread-local-storage methods and classes.

using System;
using System.Threading;

namespace ConsoleApplication11
{
class Class1
{
public void ThreadStart()
{
string str1 = "My Cookie "+
Thread.CurrentThread.GetHashCode();
Console.WriteLine("worker thread: {0}", str1);
LocalDataStoreSlot lds =
Thread.GetNamedDataSlot("COOKIE");
Thread.SetData(lds, str1);
Thread.Sleep(1);
LocalDataStoreSlot lds2 =
Thread.GetNamedDataSlot("COOKIE");
string str2 = "";
str2 = (string) Thread.GetData(lds2);
Console.WriteLine("worker thread: {0}", str2);
}

static void Main(string[] args)
{
string str1 = "My Cookie "+
Thread.CurrentThread.GetHashCode();
Console.WriteLine("main thread: {0}", str1);
LocalDataStoreSlot lds =
Thread.AllocateNamedDataSlot("COOKIE");
Thread.SetData(lds, str1);
Class1 obj = new Class1();
Thread thread = new Thread(
new ThreadStart(obj.ThreadStart));
thread.Start();
Thread.Sleep(1);
LocalDataStoreSlot lds2 =
Thread.GetNamedDataSlot("COOKIE");
string str2 = "";
str2 = (string) Thread.GetData(lds2);
Console.WriteLine("main thread: {0}", str2);
}
}
}

You could also create and start more than one thread and the behavior of the thread local storage becomes more obvious. I have played with Win32 thread-local-storage functions and created my own for portability to UNIX, but I have rarely found them very useful. I strongly believe in stateless computing and thread-local-storage contradicts this belief.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: