Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested locking misunderstanding in c#?

Can someone please explain me why we need nested locking ?

look at this example :

lock (locker)
  lock (locker)
    lock (locker)
      {
        ...
      }

enter image description here

can someone please explain (+ example will be much appreciated).

like image 916
Royi Namir Avatar asked Jun 06 '12 07:06

Royi Namir


2 Answers

Can someone please explain me why we need nested locking ?

It is only an issue because you might have nested (eg mutually recursive) calls to methods that need to lock. Those methods must allow being called with the resource already locked but they can not depend on it. So nested locking is allowed, not needed.

The code you posted (and the book you refer to) show how it works by reducing it to an inline scenario. That is not 'real' code.

The simple rule is that a thread that already owns a lock can lock it again and that the number of Exits must match the number of Enters to release the lock.

like image 91
Henk Holterman Avatar answered Oct 04 '22 23:10

Henk Holterman


There are situations whether the ability to nest locks on the same thread is very practical.

Suppose you have a class with multiple methods. Suppose you want to have a very simple locking scheme like this:

class A
{
    public void MethodOne()
    {
        using (locker)
        {
            ...body...
        }
    }

    public void MethodTwo()
    {
        using (locker)
        {
            ...body...
        }
    }
}

Now, if MethodOne calls MethodTwo, you would have a deadlock at the beginning of MethodTwo, if there wasn't a reentrant locking capability in the monitor. The thread would simply have blocked itself through the locker.

Fortunately, this example just works in .NET. The locker "knows" which thread has locked it and how many times and it will let (only) the owning thread through. The count is used to make sure that the unlock from the perspective of other waiting threads happens only when exiting MethodOne rather than when exiting MethodTwo. So this is an example of useful nested locking.

On the other hand, the example mentioned in the question seems to come from this book. The authors wanted to make it clear that nested locking is possible in .NET, automatically; but their example code is contrived and not intended to appear in anyone's code except when trying to learn how locking works under the hood.

like image 24
Jirka Hanika Avatar answered Oct 04 '22 23:10

Jirka Hanika