Thread Synchronization in C#

Thread synchronization

Thread synchronization is a technique used in threading, Which allows only one thread to access the resources for a specific time period.No other thread interrupt till current task is completed.



Thread Synchronization
Thread Synchronization

It uses 3 techniques.
  • Monitor Or Lock
  • Mutex
  • Semaphore

1.Monitor Or Lock- It uses when multi-threaded application with single process.It uses Monitor class Or Lock keyword to synchronize the multi-threaded application.

It uses "System.Threading" Namespace.
We can demonstrate the lock keyword as below. 
lock(object)
{
}

Lets understand with an example.


lock Example

class ThreadLock
    {
        public static void Main()
        {            
            ThreadLock tl = new ThreadLock();
            Thread th = new Thread(tl.ThreadRun);
            Thread th1 = new Thread(tl.ThreadRun);
            Thread th2 = new Thread(tl.ThreadRun);
            th.Start();
            th1.Start();
            th2.Start();
            Console.WriteLine("Completed Successfully.........");
            Console.Read();
        }
        Random r = new Random();
        public int num1;
        public int num2;
        public void ThreadRun()
        {
            for (long var1 = 0; var1 < 10000000; var1++)
            {
                lock (this)
                {
                    num1 = r.Next(1, 2);
                    num2 = r.Next(1, 3);
                    int result = num1 / num2;
                    num1 = 0;
                    num2 = 0;
                }
            }
        }
    }



OUTPUT
Monitor Output
Monitor-Output






Lets Understand the above program

In Main() we created 3 threads and all the threads pointing to the same method ThreadRun().

In ThreadRun() we have a long running loop and trying to divide 2 numbers. With in the for Loop we used lock synchronization technique to synchronize the program. That means only one thread can use the resources at a time and program can run smoothly.

2. Mutex-  It uses when we use multi-threaded application with single or multiple processes. It is similar to lock/Monitor. It uses Mutex class for multi-threaded application synchronization.

It use System.Threading Namespace.

It Uses 2 methods.

  • WaitOne() - It allows single thread to use the resources.
  • ReleaseMutex()- It release current thread and allow other thread to use the resource.

Skeleton of Mutex

Mutex mu=new Mutex();
mu.WaitOne();
mu.ReleaseMutex()

Lets Understand Mutex with a C# Program


class ThreadMutex
    {
        public static Mutex mut = new Mutex();
        public static int iteration =3;
        public static void Main()
        {            
            
                Thread thread1 = new Thread(Mutex_Method);
                Thread thread2 = new Thread(Mutex_Method);
                Thread thread3 = new Thread(Mutex_Method);
                thread1.Name = "Thread1";
                thread2.Name = "Thread2";
                thread3.Name = "Thread3";
                thread1.Start();
                thread2.Start();
                thread3.Start();
                Console.Read();
            
        }

        private static void Mutex_Method()
        {
            Console.WriteLine(Thread.CurrentThread.Name + " Started...");
            mut.WaitOne();
            Console.WriteLine("Currently " + Thread.CurrentThread.Name + " Entered...");
            Thread.Sleep(500);
            Console.WriteLine(Thread.CurrentThread.Name + " Done processing...");
            mut.ReleaseMutex();
            Console.WriteLine(Thread.CurrentThread.Name + " is released...");
        }
    }


Output
Monitor Output
Mutex-Output















In Main() we created 3 threads and all the threads pointing to the same method Mutex_Method().

In Mutex_Method() we use WaitOne() which signal the program to allow only one thread to use the resources.Other threads need to wait until the current thread finish it's work.

We use ReleaseMutex() which signal the program to release the current thread and allow other thread to use the resources.


3. Semaphore It is used for multi-threaded application . Unlike Monitor and Mutex it allows multiple thread based upon the value defined.

We can define Semaphore as below.

Semaphore semapr = new Semaphore(2,2);
 Where value passed in the above constructor is (2,2) 1st 2 is the Initial count and other 2 is the maximum count

It use System.Threading Namespace.

It Uses 2 methods.

  • WaitOne() - It allows defined number of threads to use the resources.
  • Release()- It release current threads and allow other thread to use the resources.


Note-Semaphore allows multiple threads(based upon the value defined in Semaphore constructor) to use the resources at a time.

Skeleton of Semaphore


Semaphore semap=new Semaphore (2,2);  //This allows 2 threads to use the resource at a time
semap.WaitOne();

semap.Release()

Lets Understand Semaphore with a C# Program


   class Semaphore_Example
    {
        public static Semaphore semapr = new Semaphore(2,2);
        public static void Main()
        {
            Thread thread1 = new Thread(Semaphore_Method);
            Thread thread2 = new Thread(Semaphore_Method);
            Thread thread3 = new Thread(Semaphore_Method);
            thread1.Name = "Thread1";
            thread2.Name = "Thread2";
            thread3.Name = "Thread3";
            thread1.Start();
            thread2.Start();
            thread3.Start();
            Console.Read();
        }

        private static void Semaphore_Method()

        {
            Console.WriteLine(Thread.CurrentThread.Name + " Started");
            semapr.WaitOne();
            
            Console.WriteLine(Thread.CurrentThread.Name + " Entered");
            Thread.Sleep(1000);
            Console.WriteLine(Thread.CurrentThread.Name + " Releasing.....");
            
            semapr.Release();
            
        }
    }



Output
Semaphore Output
Semaphore Output


















In Main() we created 3 threads and all the threads pointing to the same method Semaphore_Method().

In Semaphore_Method() we have implemented WaitOne() which signal the program to allow defined number of thread to use the resources.Other threads need to wait until the current thread release the resources.

We use Release() which signal the program to release the current threads and allow other threads for resources.

Things To Remember...

  • Lock/Monitor used to allow one thread at a time for a single process
  • Mutex is like Lock/Monitor but it allows multiple process.
  • Semaphore allows multiple threads to use the resources at a time.
  • Lock/Monitor has batter performance among all.



Thanks.................................



Share:

Multi-Threading Example in c#

Understand Multi threading



Before dive into the Thread Programming, we should know what is Thread and why should we use thread.

What is thread and Why we need Thread


Thread is a concept of C# which used to run code segment simultaneously by using multiple threads. 

Kernel schedule the threads asynchronously, which makes the application execution faster and no need to wait for a code segment to execute completely.
Thread is most important when the code segment like methods are taking time and need to wait for the method to execute the application.

Switching CPU between multiple threads to execute code segments is called Context Switching.

Description

Thread is nothing but a lightweight process.
We know each application runs using a process . That process use at least one thread.
So ultimately we can say each application use at least one thread by default. That is called Main thread
We can create child thread and assign the code segment to it.
Thread use CPU Usage efficiently.

Thread use System.Threading Namespace to use the Thread class methods and Properties.

Thread Life cycle

It goes through 4 steps as shown below.

  • New-When Only the Instance of the thread got created.
  • Running-When thread is in running state , that time Start() called.
  • Blocked or Hold state- When Thread got started but that time thread is in Hold state.
  • Complete or dead State- When thread ended and not run again.



Thread-Life-Cycle-C#
Multi-Threading Life Cycle In C#


Sample Multi-threading Program 

class Program
    {
        static void Main(string[] args)
        {
            Thread mythread1 = new Thread(method1);
            Thread mythread2 = new Thread(method2);
            mythread1.Start();
            mythread2.Start();
            Console.ReadKey();
        }

        private static void method1()
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine("Method1 " + i);
            }

        }
        private static void method2()
        {
            for (int j = 11; j <=20; j++)
            {
                Console.WriteLine( "Method2 " + j);
            }
        }        
    }

1.In the above multi-threading example we created 2 threads.
We assign the related methods to the constructor of the thread class(Highlighted).

         Thread mythread1 = new Thread(method1);            Thread mythread2 = new Thread(method2);           

2.In the next step we define 2 methods which uses loop to display numbers as shown below.

private static void method1()
        {
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine("Method1 " + i);
            }

        }
        private static void method2()
        {
            for (int j = 11; j <=20; j++)
            {
                Console.WriteLine( "Method2 " + j);
            }
        }        


3.In the next step we start the thread using Start() method as shown below .
 mythread1.Start(); mythread2.Start();

After the code we need to Run the application by using Run Icon available in Visual Studio or we can press Ctrl+f5.

We can see the the below Output.
Output
Multi-threading-Output
Multi-threading Output
















In The above image you can see the values are not printed in systematic order why?

The reason behind this is CPU is shared between two threads asynchronously. That is the  reason why both method1() and method2() run asynchronously.

Benefits of Multi-Threading Application

  1. Faster Execution.
  2. Proper utilization of CPU because of Context Switching.


Demerits of Multi-Threading Application

  1. If code segment is not taking much time , then implementing threading makes an adverse affect on the application execution time.
  2. Application may fail to show expected data if  we not implement threading in a proper way.
  3. Multi-Thread makes application more Complex , this means difficult to debug and mentain multi-threaded  application.


Conclusion

  • Multi-Threading Implementation should be proper in the application. 
  • Multi-Threading should not be used in small fast running application.
  • Multi-Thread should be used in big application where the code segment took time to execute.



Share:

Contact for Azure Training

Name

Email *

Message *

Subscribe YouTube

Total Pageviews

Popular Posts

Labels

Recent Posts