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?
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.
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.
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.
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.
My first response would be that AnotherMethod can be called directly, not going through the Main method, so therefor you might need nested locking.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With