.NET Threading Part II

Mutex & Local Thread Storage

Mutex

The last synchronization object I'll present here is the Mutex. The most useful feature of the Mutex class is that it may be named. This allows you to create two Mutex objects in different areas of code without having to share Mutex object instances. As long as the Mutex object instances have the same name, they will synchronize with each other. You could create the Mutex in two different processes on the same machine and the synchronization crosses the process boundary. Nor do you have to worry about passing the Mutex object in order to share the synchronization object between two threads or methods (see Listing 2).

Listing 2: Mutex Class

using System;
using System.Threading;

namespace ConsoleApplication10
{
    class Class1
    {
        public void ThreadStart()
        {
            Mutex mutex = new Mutex(false, "MyMutex");
            mutex.WaitOne();
            Console.WriteLine("Hello");
        }

        static void Main(string[] args)
        {
            Class1 obj = new Class1();
            Thread thread = new Thread(
                new ThreadStart(obj.ThreadStart));
            Mutex mutex = new Mutex(true, "MyMutex");
            thread.Start();
            Thread.Sleep(1000);
            Console.WriteLine("Signal");
            mutex.ReleaseMutex();
        }
    }
}

In the above listing, two separate Mutex objects are created, but the Mutex class allows the two instances to interact. The Signal will always precede the Hello in the output of this program. This is because the Mutex in the thread is created with the lock acquired. The second thread then creates the Mutex without acquiring the lock. The second thread will then wait on the mutex until the main thread releases the mutex a second later.

Thread Local Storage

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.

Listing 3: Thread Local Storage

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.

You might also like...

Comments

About the author

Randy Charles Morin

Randy Charles Morin Canada

Randy's article are Copyright 1998-2003 Randy Charles Morin

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Walking on water and developing software from a specification are easy if both are frozen.” - Edward V Berard