The ramblings of a disgruntled geek!!

Tuesday, March 03, 2009

ThreadStaticAttribute

Reminder to self:

ThreadStaticAttribute only works with static fields!

Here is why:

public class TestingTLS
{
    [ThreadStatic]
    public static int value = 0;
    [ThreadStatic]
    public int value2 = 0;   
}

public class MyClass
{
    public static void TLSTest()
    {
        TestingTLS tls = new TestingTLS();
        Dictionary<int, Thread> threads = new Dictionary<int, Thread>();
        Semaphore sem = new Semaphore(100, 100);
        long count = 0;
        for ( int i = 0 ; i < 100 ; i ++ )
        {
            Thread t = new Thread(state => {
                int tid = Thread.CurrentThread.ManagedThreadId;
                TestingTLS.value = tid; 
                Thread.Sleep(0);
                if ( tid != TestingTLS.value )
                {
                    Console.Error.WriteLine( "Value 1: {0} read {1}", tid, TestingTLS.value );
                    Interlocked.Increment(ref count);
                }
                tls.value2 = tid;
                Thread.Sleep(0);
                if ( tid != tls.value2 )
                {
                    Console.Error.WriteLine( "Value 2: {0} read {1}", tid, tls.value2);
                    Interlocked.Increment(ref count);

                }
                threads.Remove(tid);
                if ( threads.Count == 0 )
                    sem.Release();
            });
            threads.Add(t.ManagedThreadId, t);
            sem.WaitOne();
            t.Start();   
        }
        Console.WriteLine("Waiting for all threads to finish...");
        sem.WaitOne();
        Console.WriteLine("Total races: " + count);
    }
}



You will see races for value2 but not for value.

Update: The code snippet was updated, since the previous example had a race where the Total Race count would reach before all threads have finished reporting the wrong number of total races in cases where there were large number of races.

Keyboard

Keyboard
Keyboard

Blog Reading Level

blog readability test

VerveEarth

About Me

My photo

Alpha Geek. 
Aspiring Entrepreneur.