为什么嵌套锁不会导致死锁? [英] Why do nested locks not cause a deadlock?
问题描述
可能重复:结果
在C#中 重入锁
块引用>为什么这个code不会导致死锁?
私有静态只读对象=新的对象();
...
锁(一)
{
锁定(一)
{
....
}
}
解决方案如果一个线程已经持有的锁,那么它可以采取锁同样没有问题。
至于为什么的是,(为什么这是一个好主意),考虑以下情况,我们有一个明确的锁的程序的其他地方订购 - >乙:
无效F()
{
锁定(一)
{/ *做*里面的东西/}
}无效doStuff()
{
锁(B)
{
//做里面的东西B,涉及将b处于不一致的状态
F();
//多做里面的东西B,使用其一贯的再
}
}哎呦,我们只是违反了我们的锁订购和有潜在的僵局在我们的手。
我们的真正的需要能够做到以下几点:
函数doStuff()
{
锁定(一)
锁(B)
{
//做里面的东西B,涉及将b处于不一致的状态
F();
//多做里面的东西B,使用其一贯的再
}
}所以我们锁定顺序保持,无自死锁当我们调用
F()
。Possible Duplicate:
Re-entrant locks in C#Why does this code not cause a deadlock?
private static readonly object a = new object();
...
lock(a) { lock(a) { .... } }
解决方案If a thread already holds a lock, then it can "take that lock" again without issue.
As to why that is, (and why it's a good idea), consider the following situation, where we have a defined lock ordering elsewhere in the program of a -> b:
void f() { lock(a) { /* do stuff inside a */ } } void doStuff() { lock(b) { //do stuff inside b, that involves leaving b in an inconsistent state f(); //do more stuff inside b so that its consistent again } }
Whoops, we just violated our lock ordering and have a potential deadlock on our hands.
We really need to be able to do the following:
function doStuff() { lock(a) lock(b) { //do stuff inside b, that involves leaving b in an inconsistent state f(); //do more stuff inside b so that its consistent again } }
So that our lock ordering is maintained, without self-deadlocking when we call
f()
.这篇关于为什么嵌套锁不会导致死锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!