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
Post a Comment