Why moving this line cause deadlock?

1365 views c#
1

I think I am missing something obvious here:

Why does this code doesn't cause deadlock:

static void Main(string[] args)
{
    object _lock1 = new object();
    object _lock2 = new object();

    Thread code1 = new Thread(() =>
    {
        lock (_lock1)
        {

            lock (_lock2)
            {
                Console.WriteLine("A");
                Thread.Sleep(3000);
            }
        }
    });

    Thread code2 = new Thread(() =>
    {
        lock (_lock2)
        {
            lock (_lock1)
            {
                Console.WriteLine("B");
                Thread.Sleep(3000);
            }
        }
    });

    code1.Start();
    code2.Start();

    code1.Join();
    code2.Join();

    Console.WriteLine("Done");
}

But this one does:

static void Main(string[] args)
{
    object _lock1 = new object();
    object _lock2 = new object();

    Thread code1 = new Thread(() =>
    {
        lock (_lock1)
        {
            lock (_lock2)
            {
                Thread.Sleep(3000);
                Console.WriteLine("A");
            }
        }
    });

    Thread code2 = new Thread(() =>
    {
        lock (_lock2)
        {
            Thread.Sleep(3000);
            lock (_lock1)
            {
                Console.WriteLine("B");
            }
        }
    });

    code1.Start();
    code2.Start();

    code1.Join();
    code2.Join();

    Console.WriteLine("Done");
}

thanks

answered question

Add more tracing who acquired lock. But anyway both code snippets are bad and can cause deadlocks. It just coincidence, that first snippet didn't get into deadlock.

1 Answer

11

To help explain the "deadlock" question -

Use Thread.Sleep if you really want to suspend the thread.

But in this case where you don't want to suspend the thread, just suspend the 'task'.

Use some like this:

await Task.Delay(myDuration);

This will not suspend the entire thread, but just the single task you want to suspend.

All other tasks on the same thread can continue running...

posted this

Have an answer?

JD

Please login first before posting an answer.