Search code examples
c#.netlockingdeadlock

Why doesn't Lock'ing on same object cause a deadlock?


If I write some code like this:

class Program {
    static void Main(string[] args) {
        Foo();
        Console.ReadLine();
    }

    static void Foo() {
        lock(_lock) {
            Console.WriteLine("Foo");
            Bar();
        }
    }

    static void Bar() {
        lock(_lock) {
            Console.WriteLine("Bar");
        }
    }
    
    private static readonly object _lock = new object();
}

I get as output:

Foo
Bar

I expected this to deadlock, because Foo acquires a lock, and then waits for Bar to acquire the lock. But this doesn't happen.

Does the locking mechanism simply allow this because the code is executed on the same thread?


Solution

  • For the same thread a lock is always reentrant, so the thread can lock an object as often as it wants.