Library tutorials & articles

.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.

Comments

  1. 10 Nov 2004 at 21:30
    Greetings-
    I have been doing alot of reading in this area and am frankly confused on which model/classes to use for a specific implementation I am working on. Perhaps you could shed some light.

    I have a large treeview on a UI thread, with nodes that contain collections of images that take a long time to render previews for in a panel. I would like to let a worker thread render the set of previews based on the treeview node selected, passing each preview back to the ui thread as they complete. Of course, it's bad form to have a worker thread access objects in the UI thread.

    I have tried async delegate calls and got it working on the UI thread, but it still locks the UI while it's rendering the previews. I am confused about wether to use events, a ThreadPool, Mutex stuff, or what?

    Can you help me out here?

    Many Thanks
  2. 12 Feb 2004 at 11:57

    hi, interesting article you've written here. just one question, and that is do you know of a function in .NET/C# equivalent to the old PostThreadMessage. The intention here is not to pass any information to a spawned thread via the LPARAM parameter, but rather just to inform the thread of the fact that some information is ready for them to collect (available at a singleton object which is made thread-safe). I tried using the approach of firing events and having the event handled by a delegate but only managed to make this work in the context of the same thread, not across threads. Any ideas?


    Thanks


    Alastair.

  3. 01 Jan 1999 at 00:00

    This thread is for discussions of .NET Threading Part II.

Leave a comment

Sign in or Join us (it's free).

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

Related podcasts

  • A Practical Look at Silverlight 2 Part 1

    Now that Silverlight 2 is at the Olympics and making a big splash, we wanted to explore this fascinating technology more. Microsoft Silverlight 2 is a cross-browser, cross-platform, and cross-device plug-in for delivering the next generation of .NET based media experiences and rich interactive ap...

Events coming up

  • Mar 15

    DevWeek 2010

    London, United Kingdom

    DevWeek is Europe’s leading independent conference for software developers, database professionals and IT architects, and features expert speakers on a wide range of topics, including .NET 4.0, Silverlight 3, WCF 4, Visual Studio 2010, REST, Windows Workflow 4, Thread Synchronization, ASP.NET 4.0, SQL Server 2008 R2, LINQ, Unit Testing, CLR & C# 4.0, .NET Patterns, WPF 4, F#, Windows Azure, ADO.NET, Entity Framework, Debugging, T-SQL Tips & Tricks, and more.

Want to stay in touch with what's going on? Follow us on twitter!