锁内锁 [英] lock inside lock
问题描述
我想知道这种构造是否会导致错误:
I'm wondering if this construction will cause an error:
lock(sync)
{
// something
lock(sync)
{
//something
lock(sync)
{
//something
}
}
}
我已经运行了这段代码,看起来还不错,但是在某些情况下可能会引发错误?
I've run this code, and it seems fine, but maybe in some circumstances an error may be thrown?
推荐答案
lock
是针对Monitor.Enter
和Monitor.Exit
:
lock
is a wrapper for Monitor.Enter
and Monitor.Exit
:
lock
关键字在块的开头调用Enter
,在块的结尾调用Exit
.从前者的文档中:
The
lock
keyword callsEnter
at the start of the block andExit
at the end of the block. From the former's documentation:
从Monitor.Enter
的文档中:
From the documentation for Monitor.Enter
:
同一线程多次调用
Enter
而不阻塞它是合法的;但是,必须等待相等数量的Exit
调用,然后其他等待该对象的线程才能解除阻塞.
It is legal for the same thread to invoke
Enter
more than once without it blocking; however, an equal number ofExit
calls must be invoked before other threads waiting on the object will unblock.
由于对Enter
和Exit
的调用是配对的,因此您的代码模式具有明确的行为.
Because the calls to Enter
and Exit
are paired, your code pattern has well defined behaviour.
但是请注意,不能保证lock
是无异常的构造:
Note, however, that lock
is not guaranteed to be an exception-less construct:
如果
Interrupt
中断正在等待输入lock
语句的线程,则会抛出ThreadInterruptedException
.
A
ThreadInterruptedException
is thrown ifInterrupt
interrupts a thread that is waiting to enter alock
statement.
这篇关于锁内锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!