Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't this lock statement work?

Tags:

c#

locking

class Program
{
    static object test = new object();
    static void Main(string[] args)
    {
        new Program().test2();
        Console.ReadKey();
    }

    public void test1()
    {
        lock (test)
        {
            Console.WriteLine("test1");
        }
    }

    public void test2()
    {
        lock (test)
        {
            test1();
            Console.WriteLine("test2");
        }
    }
}

Is the code above supposed to first finish statements in lock statement of test2() then go to the test1()? (i.e. Doesn't the output supposed to be like this? : test2 test1 )

like image 443
armin Avatar asked Nov 27 '22 14:11

armin


1 Answers

No. The sequence of events (identation represents call stack or logical operations) is:

  • Main calls test2
    • test2 attempts to acquire the monitor associated with the test object (start of the lock statement)
      • Monitor is currently unowned. Success!
      • The current thread now "owns" that monitor, with a count of 1
    • test2 calls test1
      • test1 attempts to acquire the monitor for the test object (start of the lock statement)
        • Monitor is currently owned... but by the current thread. Success!
        • The current thread still "owns" the monitor, with a count of 2
      • test1 prints "test1"
      • test1 releases the monitor (end of the lock statement)
        • The current thread still "owns" the monitor, with a count of 1
      • test1 returns
    • test2 prints "test2"
    • test2 releases the monitor (end of the lock statement)
      • The monitor is now unowned (so another thread could acquire it)
    • test2 returns

It's important to note that monitors are re-entrant - if the current thread already owns the monitor, then another attempt to acquire it will just increase the count, rather than blocking.

If monitors weren't re-entrant, the output wouldn't be "test2, test1" - it would just be deadlock.

like image 194
Jon Skeet Avatar answered Dec 05 '22 09:12

Jon Skeet