-1
class Program
    {
        static void Main(string[] args)
        {
            Thread thread1 = new Thread((ThreadStart)DLockSample.FunctionA);
            Thread therad2 = new Thread((ThreadStart)DLockSample.FunctionB);
            thread1.Start();
            therad2.Start();
        }
    }

    public class DLockSample
    {
static object object1 = new object();
        static object object2 = new object();

        public static void FunctionA()
        {
            lock (object1)
            {
                Thread.Sleep(1000);
                lock (object2)
                {
                    Thread.Sleep(1000);
                    Console.WriteLine("heart beat - object2");
                }
            }
        }
        public static void FunctionB()
        {
            lock (object2)
            {

                lock (object1)
                {
                    Thread.Sleep(1000);
                    Console.WriteLine("heart beat - object1");
                }
            }
        }    }
sawer
  • 1
  • This was obviously intentional. It isn't very interesting, just swap the locks in FunctionB. Be sure to use the [homework] tag if you want an educational answer. – Hans Passant Feb 02 '11 at 13:06

2 Answers2

1

Always enter the locks in the same order in all threads. See also hierarchy of critical sections I.e. FunctionB needs to be:

public static void FunctionB()
        {
            lock (object1)
            {

                lock (object2)
    ...
Community
  • 1
  • 1
Suma
  • 33,181
  • 16
  • 123
  • 191
  • I agree. But code block is purposeful to simulate scenarios wherein we should be able propose some suitable solution. – sawer Feb 02 '11 at 12:23
1

That's a pretty abstact problem to fix. Just a few tips:

  • Always lock on objects in the same order
  • If it's impossible to lock in the same order, use object's fields to preserve the order (for example, if A.Id > B.Id then always lock on A before B).
Andrey Taptunov
  • 9,367
  • 5
  • 31
  • 44
  • Like the A.Id > B.Id idea. You do need to ensure that the value you use for the comparison can not/will not change in either thread or you may still find that the second thread locks in a different order... – Marjan Venema Feb 02 '11 at 12:21
  • Code block is purposeful to simulate deadlock scenarios wherein we should be able propose some suitable solution. If you are not happy with the above code block then can you write an example which simulate deadlock ? And a propossed solution....Thanks – sawer Feb 02 '11 at 12:26
  • Your questions says "how do i fix this". This is the answer. If your question is different, please, update it, so that even those without telepathy ability can read the question. – Suma Feb 02 '11 at 13:03