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
  • 19,792
  • 9
  • 57
  • 71
DeepSpace101
  • 12,552
  • 8
  • 74
  • 123

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
  • 19,792
  • 9
  • 57
  • 71
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,351
  • 12
  • 33