Monday 19 October 2015

Deadlock in c#? What is deadlock in c#?

Deadlock is a situation where an application locks up because more than one process are waiting for each other to finish.
Deadlock occurs when each of two threads try to acquire a lock on a resources already locked by another.
Thread 1 locked on resources 1 tries to acquire a lock on resources 2. At the same time, thread 2 has a lock on resources 2 and tries to acquire lock on resources 1. These two threads never give up their locks, hence a Deadlock occurs.

Example:-

class Program
    {
        private static object staticObjLock1 = new object();
        private static object staticObjLock2 = new object();
 
 
        static void Main()
        {
        
            Thread thread1 = new Thread(DoWork1);
            Thread thread2 = new Thread(DoWork2);
 
            thread1.Start();
            thread2.Start();
 
            thread1.Join();
            thread2.Join();
 
            Console.WriteLine("Processing done!");
            Console.ReadLine();
 
 
         }
 
        private static void DoWork1()
        {
            lock (staticObjLock1)
            {
                Console.WriteLine("try to accquire lock on objectB");
                Thread.Sleep(1000);
                lock (staticObjLock2)
                {
                    // this will never execute
                    Console.WriteLine("in DoWork2 critical section");
                }
            }
        }
        private static void DoWork2()
        {
            lock (staticObjLock2)
            {
                Console.WriteLine("try to accquire lock on objectA");
                //Thread.Sleep(1000);
                lock (staticObjLock1)
                {
                    // this will never execute
                    Console.WriteLine("in DoWork2 critical section");
                }
            }
        }
 
    }

No comments:

Post a Comment

Note: only a member of this blog may post a comment.