Under what conditions can a thread enter a lock (Monitor) region more than once concurrently?

前端 未结 6 1823
一个人的身影
一个人的身影 2021-01-05 04:45

(question revised): So far, the answers all include a single thread re-entering the lock region linearly, through things like recursion, where you can trace the steps of a s

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-05 05:14

    Re-Entrance is possible if you have a structure like so:

    Object lockObject = new Object(); 
    
    void Foo(bool recurse) 
    {
      lock(lockObject)
       { 
           Console.WriteLine("In Lock"); 
           if (recurse)  { foo(false); }
       }
    }
    

    While this is a pretty simplistic example, it's possible in many scenarios where you have interdependent or recursive behaviour.

    For example:

    • ComponentA.Add(): locks a common 'ComponentA' object, adds new item to ComponentB.
    • ComponentB.OnNewItem(): new item triggers data-validation on each item in list.
    • ComponentA.ValidateItem(): locks a common 'ComponentA' object to validate the item.

    Same-thread re-entry on the same lock is needed to ensure you don't get deadlocks occurring with your own code.

提交回复
热议问题