Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested locking in C#

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?

like image 363
Alexandre Avatar asked Nov 22 '12 10:11

Alexandre


People also ask

What is nested lock?

Nested Locking. A thread can repeatedly lock the same object, either via multiple calls to Monitor.Enter, or via nested lock statements. The object is then unlocked when a corresponding number of Monitor.Exit statements have executed, or the outermost lock statement has exited.

Why do we use lock statement in C?

The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.

What is locking in coding?

Code locking is done at the function call level and guarantees that a function executes entirely under the protection of a lock. The assumption is that all access to data is done through functions. Functions that share data should execute under the same lock.

What is lock in c3?

The lock keyword is used to get a lock for a single thread. A lock prevents several threads from accessing a resource simultaneously. Typically, you want threads to run concurrently. Using the lock in C#, we can prevent one thread from changing our code while another does so.


2 Answers

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

like image 51
Arcturus Avatar answered Sep 23 '22 13:09

Arcturus


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?

like image 22
Tilak Avatar answered Sep 24 '22 13:09

Tilak