locked
Creating a deadlock example C# Exam 70-483: error? RRS feed

  • Question

  • I have the book Exam Ref 70-483 Programming in C#.

    Listing 1-37(Page 33) shows an example of a deadlock.

        public class Program
        {
            static void Main(string[] args)
            {
                object lockA = new object();
                object lockB = new object();
                var up = Task.Run(() =>
                {
                    lock (lockA)
                    {
                        Thread.Sleep(1000);
                        lock (lockB)
                        {
                            Console.WriteLine("Locked A and B");
                        }
                    }
                });
                lock (lockB)
                {
                    lock (lockA)
                    {
                        Console.WriteLine("Locked B and A");
                    }
                }
                up.Wait();
            }
        }

    In the paragraph, it says: Because both locks are taken in reverse order, a deadlock occurs. The first Task locks A and waits for B to become free. The main thread, however, has B locked and is waiting for A to be released.

    However I tried the code, there was no deadlock at all.

    Anything wrong?

    Monday, January 5, 2015 8:19 PM

Answers

  • You didn't get any deadlock because the main thread completed before the secondary thread had the time to take its first lock. If you want to see the deadlock, add a Thread.Sleep(1000) in the main thread after taking the lock on lockB (in the same way that the secondary thread does a Sleep after taking lockA).
    Tuesday, January 6, 2015 7:56 AM