Multithreading: the Mutex kernel object

Ok, now that we understand the basics of waiting on a kernel object, it’s time to keep going and start looking at some code (hurray!). Today we’re going to take a look at the mutex kernel object. In .NET, a mutex kernel object is represented by an instance of type Mutex. As we’ve seen yesterday,  the Mutex type sublcasses the WaitHandle type.

In practice, we use mutexes to build critical regions, ie, to delimit certain regions of code so that they can only be executed by a thread at a time. Since a mutex is a kernel object, you’re right if you’re thinking that mutual exclusion is achieved through atomic state transition (signaled to non signaled).

When a mutex is in a signaled state, it can be taken by any thread that enters the region delimited by it. When that happens, the mutex transitions to the non signaled state and the thread that entered that critical region owns the mutex (this is an important concept that you should keep in mind – notice that not all kernel objecs have the concept of ownership). All other threads that try to enter the critical region will be blocked.

When a thread that owns a mutex exits a critical region, it must always signal that in order to release ownership so that other threads can be awakened and enter that region. In practice,entering a critical region is done by waiting on a mutex and leaving a critical section consists (simply) on releasing it (as we’ll see in the snippet I’m showing below).

Since mutexes support the concept of ownership,it’s interesting to try to understand what happens when a) you forget to call release on a mutex, b) you have reentrancy (that is, a thread that has already acquired the mutex acquires it again before releasing it) and c) you call release on a mutex you don’t own.

Lets start with scenario a), which is generally know as abandoned mutex. Since a mutex is a kernel object, when a mutex is abandoned (ie, when a thread that owns it terminates and doesn’t release it), we can count on the OS to help us. If the OS detects an abandoned mutex and sees that it has waiting threads, it will wake one of them as if the mutex had been released and, in the case of managed code, it will throw an AbandonedMutexException exception. Notice that even though it throws, the new thread that was awaked acquires the mutex successfully (which means that you need to be prepared for this and you shouldn’t forget to release the mutex at the end of the critical region). Even though you can recover from this exception, you probably should proceed with caution because an abandoned mutex might indicate some unknown error in your program.

Now, what happens when you have reentrancy? Well, it will succeed because mutexes support the concept of ownership and use an internal field for keeping track of the number of the times the owner thread has waited  on it (recall that waiting will succeed immediately when a mutex is signaled or when the “current” thread owns that mutex). The only thing you should keep in mind is that if you acquire a mutex several times, then you must pair those acquisitions with release calls.

Releasing a mutex (option c) can only have one result: an exception will be thrown.

Ok, enough theory…time so show some code. The first time you need to do is to create a mutex. In .NET, you can do that by using one of the following constructors exposed by the Mutex type:

public Mutex();
public Mutex(bool initiallyOwned);
public Mutex(bool initiallyOwned, string name);
public Mutex(bool initiallyOwned, string name, out bool createdNew);
public Mutex(bool initiallyOwned, string name, out bool createdNew, MutexSecurity mutexSecurity);

As you can see, we have several options. The default constructor creates a new mutex in a signaled state. If that is not what you want, you should use one of the overloads which receive the initiallyOwned parameter (passing true to this results in getting a non signaled mutex owned by the thread).

The overloads that receive a name let you set the mutex name (kernel objects can be named which means that they can easily be shared across processes. We’ll come back to this topic in the future). There are also a couple of overloads with an out parameter. These are useful when you need to know it the created mutex is really a new mutex (when you try to create a named mutex and there’s already one with that name, the constructor will return a reference to that instance. In this case, the createdNew will let you know if the returned mutex already exists).

Finally, the overload that receives a MutexSecurity parameter lets you set up the ACL for this kernel object. There are a couple of possible results from all these combinations and I’ll return to them in a future post.

As we’ve seen, we acquire a mutex by calling one of the WaitXXX methods and we should also signal the exit of the critical region by calling ReleaseMutex (notice that this *might* release the ownership of the mutex and let other threads enter the region).

When we’re really done with the mutex, we’re supposed to close it by calling Close or Dispose (recall that WaitHandle implements the IDisposable interface). Ok, here’s the dumbest example I could write in 30 seconds to show the usage of these methods:

static void Main(string[] args) {
   Thread secondary;
   var mutex = new Mutex();//owned signaled mutex
   try {
      secondary = new Thread(() => {
                                         Console.WriteLine("secondary thread");

       secondary.Start(); //will wait for release of main
       Console.WriteLine("Primary thread");
    finally {

A couple of observations for the previous code:

  • we start by creating a new signaled unnamed mutex owned by the main thread and we acquire it immediately by calling the WaitOne method.
  • we use a try/finally block to ensure that the mutex is released. This ensures that the secondary thread gets a chance for running;
  • we close the mutex by invoking the Close method. This is important and it ends up releasing the OS mutex kernel object encapsulated by the managed Mutex instance.

There are still a couple of cases I think are worth showing, but I’ll leave them for future posts. Keep tuned for more on multithreaded apps!


~ by Luis Abreu on May 14, 2009.

8 Responses to “Multithreading: the Mutex kernel object”

  1. Just wanted to say you all have a great forum. Seems like a good place I can actually be a part of. 🙂

  2. Just wanted to say hi and see how everyone”s doing – I”m new to the forum.

  3. with the economy the way it is everyone is looking to work from home right now. There are a lot of bad places out there that aren”t very legit
    the hard thing to do is to find the difference between them. Thankfully there are certain program that are certainly legit.
    Such as Google Startup This place was very legit and even came back with a 30 day refund and a free trial of 14 days.
    Within 2 weeks of me starting this up I made over 500$ and it was only my first 2 weeks! i”m looking foward to the upcoming weeks.
    Kinda crazy to realize that while i”m outside rakeing the leaves or setting up my xmas lights i”m actually still making money.
    Here”s the site if you wanna check it out.

  4. Hello all,

    My name is Joe, I just wanted to introduce myself since I am new to this site…

    I am new to the internet but I am learning alot real fast!

    I”m a Hair Stylist and devoted father.

    The things I love most in life are family, friends and racing.

    On week days you”ll usually find me riding my bike. On the weekends I like to party and enjoy the outdoors.

    My idea of the perfect day would start with breakfast. And then I”d go to the drag races. Later I”d eat a great dinner from Dinosaur Bar-B-Que. And I”d top it all off by snuggling with my girlfriend.

    I also love rap videos.

    Anyways it”s wonderfull to be a part of your site!

    Thank you

  5. Hello
    I need some advice
    I really want to buy TV Stands or Entertainment Stands For a loft I”mclosing on.
    Can anyonegive me a good recommendation of where is the topdeal on these? I live in Philly and I heard that the big thing about these tv stands is the cost of shipping and installation.
    I also found this great article about wiring Entertainment Centers
    looking forward to your reply

  6. My computer detected my iPhone, but the iTunes running on the computer did not. How do I get my music on the iPhone.

    unlock iphone 3g

  7. Club Penguin Cheats provides you with a Club Penguin Money Maker that allows you to gain a lot of coins in Club Penguin.
    Club Penguin Cheats also provides you with Club Penguin Trackers such as a Club Penguin Aunt Arctic Tracker, a Club Penguin Cadence Tracker, a Club Penguin Gary Tracker, a Club Penguin Band Tracker, a Club Penguin Rockhopper Tracker, and a Club Penguin Sensei Tracker.
    Last,Club Penguin Codes gives you Club Penguin Bots

  8. Hi There I”d love to thank you for such a terrific quality forum!
    Just thought this is a nice way to make my first post!
    The only right way grow fortune it is usually a wise idea to begin a savings or investing strategy as early in life as imaginable. But don”t fear if you have not began saving your assets until later on in life. As a consequence of honest work, that is looking up on the best investment vehicles for your money you can slowly but surely increase your finances so that it adds up to a huge sum by the period you hope to retire. Scout out all of the available asset classes from stocks to real estate as investments for your money. A researched and diversified portfolio of investments in various asset classes will help your money multiply throughout the years.

    -Ashlee Markgraf
    currency exchange rates

Leave a Reply

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

You are commenting using your 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

%d bloggers like this: