Re-entrant locks in C#

30,823

Solution 1

No, not as long as you are locking on the same object. The recursive code effectively already has the lock and so can continue unhindered.

lock(object) {...} is shorthand for using the Monitor class. As Marc points out, Monitor allows re-entrancy, so repeated attempts to lock on an object on which the current thread already has a lock will work just fine.

If you start locking on different objects, that's when you have to be careful. Pay particular attention to:

  • Always acquire locks on a given number of objects in the same sequence.
  • Always release locks in the reverse sequence to how you acquire them.

If you break either of these rules you're pretty much guaranteed to get deadlock issues at some point.

Here is one good webpage describing thread synchronisation in .NET: http://dotnetdebug.net/2005/07/20/monitor-class-avoiding-deadlocks/

Also, lock on as few objects at a time as possible. Consider applying coarse-grained locks where possible. The idea being that if you can write your code such that there is an object graph and you can acquire locks on the root of that object graph, then do so. This means you have one lock on that root object and therefore don't have to worry so much about the sequence in which you acquire/release locks.

(One further note, your example isn't technically recursive. For it to be recursive, Bar() would have to call itself, typically as part of an iteration.)

Solution 2

Well, Monitor allows re-entrancy, so you can't deadlock yourself... so no: it shouldn't do

Solution 3

If a thread is already holding a lock, then it will not block itself. The .Net framework ensures this. You only have to make sure that two threads do not attempt to aquire the same two locks out of sequence by whatever code paths.

The same thread can aquire the same lock multiple times, but you have to make sure you release the lock the same number of times that you aquire it. Of course, as long as you are using the "lock" keyword to accomplish this, it happens automatically.

Solution 4

No, this code will not have dead locks. If you really want to create deadlock simplest one requires at-least 2 resources. Consider dog and the bone scenario. 1. A dog has full control over 1 bone so any other dog has to wait. 2. 2 dog with 2 bones are minimum required to create a deadlock when they lock their bones respectively and seek others bone too.

.. so on and so forth n dogs and m bones and cause more sophisticated deadlocks.

Share:
30,823
Guy
Author by

Guy

I am a consultant specializing in TypeScript/React/JavaScript/Node.js Full Stack. I also have a strong background in C#/.Net. I am available for hire.

Updated on July 26, 2022

Comments

  • Guy
    Guy almost 2 years

    Will the following code result in a deadlock using C# on .NET?

     class MyClass
     {
        private object lockObj = new object();
    
        public void Foo()
        {
            lock(lockObj)
            { 
                 Bar();
            }
        }
    
        public void Bar()
        {
            lock(lockObj)
            { 
              // Do something 
            }
        }       
     }
    
  • Marc Gravell
    Marc Gravell over 15 years
    Especially in different sequences.
  • Marc Gravell
    Marc Gravell over 15 years
    Re recursion; indeed; for Guy's benefit, the term is re-entrant
  • Jon Skeet
    Jon Skeet over 15 years
    Note that that's true for monitors, but not necessarily other kinds of lock.
  • Jon Skeet
    Jon Skeet over 15 years
    (Not wishing to imply that you didn't know that, of course - just that it's an important distinction :)
  • Jeffrey L Whitledge
    Jeffrey L Whitledge over 15 years
    That's a good point. I was actually going to change "lock" to "monitor" throughout, but then I got distracted. And lazy. And the behavior is also true for Windows mutex kernal objects, so I figured, close enough!
  • Neil Barnwell
    Neil Barnwell about 13 years
    This question seems to get quite a bit of attention so I've updated my answer with a couple of other notes that I've come up with since I first wrote it.
  • bobroxsox
    bobroxsox almost 10 years
    Actually, I don't think the order in which you release locks matters. The order in which you choose them definitely does, but as long as releasing the lock isn't conditional upon anything (you can release at any time), you should be fine as long as you release all the locks that you have acquired.