c# - Why do nested locks not cause a deadlock? -


possible duplicate:
re-entrant locks in c#

why code not cause deadlock?

   private static readonly object = new object(); 

...

   lock(a)    {       lock(a)       {          ....       }    } 

if thread holds lock, can "take lock" again without issue.


as why is, (and why it's idea), consider following situation, have defined lock ordering elsewhere in program of -> b:

void f() {     lock(a)     { /* stuff inside */ } }  void dostuff() {     lock(b)     {         //do stuff inside b, involves leaving b in inconsistent state         f();         //do more stuff inside b consistent again     } } 

whoops, violated our lock ordering , have potential deadlock on our hands.

we really need able following:

function dostuff() {     lock(a)     lock(b)     {         //do stuff inside b, involves leaving b in inconsistent state         f();         //do more stuff inside b consistent again     } } 

so our lock ordering maintained, without self-deadlocking when call f().


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -