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.
Here is the class:
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!");
}
}
}
Output:
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?
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.