Thread Synchronization with Mutex Construct

What is Mutex and how to synchronize threads using mutex


Category: Multithreading Tags: C#


Introduction

        Mutex construct is used in thread synchronization which provides facility to grant access of shared resource to only one thread at a time.

Implementation

        To understand mutex observe code below:

class MutexConstruct
{
    const string MutexString = "MutexString";
    public void Fun()
    {
        using (var m = new Mutex(false, MutexString))
        {
            if (m.WaitOne(5000, false))
            {
                Console.WriteLine("{0} is running", Thread.CurrentThread.Name);
                Console.ReadLine();
                m.ReleaseMutex();
            }
            else
            {
                Console.WriteLine("Mutex can not be acquired by {0}", Thread.CurrentThread.Name);
            }
        }
    }
}

Above we can see inside function FUN we create object of mutex passing false which sets initiallyOwned property of mutex and let first thread acquire the mutex. MutexString is required to give mutex a name which is required to keep track of all created mutex with same name.
Above we can see WaitOne method will return true or false, if thread gets access it will return true else it waits for 5 seconds, even after 5 seconds thread is unable to acquire mutex it returns false. We can execute above code from Main like:

MutexConstruct c = new MutexConstruct();
Thread t1 = new Thread(c.Fun);
t1.Name = "t1";
Thread t2 = new Thread(c.Fun);
t2.Name = "t2";
t1.Start();
t2.Start();
t1.Join();
t2.Join();

Above code starting two threads t1 and t2. When t1 starts it immediately acquires mutex and enters if block and prints “t1 is running” but when t2 starts it has to wait for 5 seconds. If within 5 seconds user gives input for line Console.ReadLine() t1 will release mutex in next line and t2 will print “t2 is running” so output will be :
t1 is running
t2 is running


If user doesn’t press enter before 5 seconds, t2 will have to execute else block and output of code will be:
t1 is running
Mutex can not be acquired by t2


Like 1 Person
Last modified on 15 June 2018
Nikhil Joshi

Nikhil Joshi
Ceo & Founder at Dotnetlovers
Atricles: 132
Questions: 9
Given Best Solutions: 9 *

Comments:

No Comments Yet

You are not loggedin, please login or signup to add comments:

Existing User

Login via:

New User



x