65.9K
CodeProject is changing. Read more.
Home

Using ThreadStaticAttribute

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.67/5 (2 votes)

Oct 11, 2013

CPOL

1 min read

viewsIcon

12595

This is an attribute that indicates that the variable has one instance for each thread. This is a variation of the static variables. Static variables

This is an attribute that indicates that the variable has one instance for each thread. This is a variation of the static variables. Static variables have one instance throughout the lifecycle of the program. A variable marked with [ThreadStatic] has one instance per thread in the program.

The syntax is shown below in C#
[ThreadStatic]
static int someValue;

To better understand this key, let us consider the following program

using System;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        public static int accessed = 0;

        [ThreadStatic]
        public static int accessedInaThread = 0; //we want this variable to be considered static per thread

        static void Main(string[] args)
        {
            Program prog = new Program();
            
            //define the threads
            Thread thread1 = new Thread(new ThreadStart(prog.ThreadFunc1));
            Thread thread2 = new Thread(new ThreadStart(prog.ThreadFunc2));

            //start thread1
            thread1.Start();
            //wait for thread1 to finish
            thread1.Join();
            
            //start thread2
            thread2.Start();
            //wait for thread2 to finish
            thread2.Join();
        }

        public void ThreadFunc1()
        {
            accessed++;
            accessedInaThread++;
            Console.WriteLine("value of accessed in Thread1: " + accessed.ToString());
            Console.WriteLine("value of accessedInaThread in Thread1: " + accessedInaThread.ToString());
        }

        public void ThreadFunc2()
        {
            accessed++;
            accessedInaThread++;
            Console.WriteLine("value of accessed in Thread2: " + accessed.ToString());
            Console.WriteLine("value of accessedInaThread in Thread2: " + accessedInaThread.ToString());
        }
    }    
}

Here accessed is a static variable and accessedInaThread is a ThreadStatic variable. These variables are accessed and changed in two different threads. Note the output of the program:

value of accessed in Thread1: 1
value of accessedInaThread in Thread1: 1
value of accessed in Thread2: 2
value of accessedInaThread in Thread2: 1

Here the threadstatic variable has a different copy for each thread. Hence, the change in value in thread1 does not impact the value in thread2.