vote buttons
1
1
beginner
0
intermediate
0
advanced

Consider the following code snippet:


lock (_lockObj)
  lock (_lockObj)
  {
    //Some code
  }
On line 2 we are again trying to obtain a lock on the same object. Would this cause a deadlock?


04-Nov-2014 05:00 UTC
K Bonneau
350

1 Answers

vote buttons
1

No. The code snippet in the question wont cause any issues as a thread can take a lock on the same object any number of times. However the lock will only be released for other threads when the code comes out of all the lock blocks.

Infact nested locks are very useful in cases where one function which is inside a lock calls another function as shown in following example. 


void OuterFunction()
{
  lock (_locker)
  {
     InnerFunction();
  }
}
 
void InnerFunction()
{
  //The following lock would still be taken even if the thread already has
  //obtained a lock on the same object before. (This is called re-entrancy)
  lock (_locker) { //Some code }
}
If nested locks were not allowed, we would be forced to choose two different objects for locking in either function, and when we use multiple objects for locking in such nested scenarios we need to be very careful to maintain the same locking order as if the locking order is reversed that would cause a deadlock. Nested locking saves us from such maintenance. 


04-Nov-2014 05:10 UTC
K Bonneau
350