0

I understand this is a single threaded example and this would lock in a multi-threaded example. But given the execution sequence, shouldn't the lock be consumed by the parent, therefore starving the child even in a single thread situation?

class Program
{
    static readonly object Lock = new object();

    static void Main(string[] args)
    {
        Console.WriteLine("Main start");
        Parent();
        Console.WriteLine("Main end");
        Console.ReadLine();
    }

    static void Parent()
    {
        lock (Lock)
        {
            Console.WriteLine("Parent start");
            Child();
            Console.WriteLine("Parent end");
        }
    }

    static void Child()
    {
        lock (Lock)
        {
            Console.WriteLine("Child start");
            Console.WriteLine("Child end");
        }
    }
}

Console output

Main start
Parent start
Child start
Child end
Parent end
Main end

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
DeepSpace101
  • 13,110
  • 9
  • 77
  • 127

2 Answers2

1

a thread can acquire a lock again if it is the one who have taken the lock.

The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
1

Synchronization simply means two different "threads" can't access the sections that are protected by the same Lock. However, this is a single thread. The thread owns the lock, so it is allowed to continue.

Daniel
  • 4,481
  • 14
  • 34