7

I'm learning multi-threading in C# and I saw a code below

static readonly object _locker = new object();

static void Main()
{
  lock (_locker)
  {
     AnotherMethod();
     // ...some work is going on
  }
}

static void AnotherMethod()
{
  lock (_locker) { Console.WriteLine ("Another method"); }
}

I wonder when does it require to use nested locking? Why don't use only one lock in this case?

Alexandre
  • 13,030
  • 35
  • 114
  • 173
  • if `AnotherMethod` is used somewhere else too (and not only in `Main`)... – Yahia Nov 22 '12 at 10:27
  • 1
    The code is truly redundant. The outer lock(_locker) is not necessary. Except if AnotherMethod() would be public and used from somewhere else. – Matthias Nov 22 '12 at 10:27

2 Answers2

4

My first response would be that AnotherMethod can be called directly, not going through the Main method, so therefor you might need nested locking.

Arcturus
  • 26,677
  • 10
  • 92
  • 107
1

To allow re-entrant code.

Your example is not appropriate. Locks are used to provide controlled access to critical section.

If one critical section invokes another critical section, then deadlock would occur. To prevent this, re-entrant code is allowed.

Why do nested locks not cause a deadlock?

Community
  • 1
  • 1
Tilak
  • 30,108
  • 19
  • 83
  • 131
  • I don't understand the conception of re-entrant code. My code is also re-entrant like here http://stackoverflow.com/questions/391913/re-entrant-locks-in-c-sharp. When is it going to be used? – Alexandre Nov 22 '12 at 11:02