我已经写了什么,我觉得应该是一个僵局有效的情况下进行测试。看来,一旦锁定
已获得了一个类的实例,该实例并不需要重新获得锁定
了,即使我明确地尝试,应该锁定
再调用另一个方法。
I've written a test of what I think should be a valid case for a deadlock. It appears that once the lock
has been acquired by an instance of the a class, that instance doesn't need to re-acquire the lock
anymore even if I explicitly try to call another method that should lock
again.
下面是类:
internal class Tester
{
private readonly object _sync = new object();
public Tester() { }
public void TestLock()
{
lock (_sync)
{
for (int i = 0; i < 10; i++)
{
Deadlock(i);
}
}
}
private void Deadlock(int i)
{
lock (_sync)
{
Trace.WriteLine(i + " no deadlock!");
}
}
}
输出:
0无僵局! 1没有僵局! 2没有僵局! 3没有僵局! 4没有僵局! 5没有僵局! 6没有僵局! 7没有僵局! 8没有僵局! 9没有僵局!
0 no deadlock! 1 no deadlock! 2 no deadlock! 3 no deadlock! 4 no deadlock! 5 no deadlock! 6 no deadlock! 7 no deadlock! 8 no deadlock! 9 no deadlock!
我本来以为,这将导致死锁......有谁能够阐明一些这?
I would have thought that this would cause a deadlock... can anybody shed some light on this?
推荐答案
在.NET锁是可重入。从其它线程只收购被阻止。当同一线程锁定该同一对象多次,它简单地递增的计数器,并且当释放时它递减。当计数器降为零,这个锁是实际发布从其他线程访问。
Locks in .NET are reentrant. Only acquisitions from other threads are blocked. When the same thread locks the same object multiple times, it simply increments a counter, and decrements it when released. When the counter hits zero, the lock is actually released for access from other threads.
相关推荐
最新文章