Avoid deadlock when the order of acquisition of locks is not guaranteed
Suppose that I have the following class:
public class BagWithLock
{
private readonly lockObject = new object();
private object data;
public object Data
{
get { lock (lockObject) { return data; } }
set { lock (lockObject) { data = value; } }
}
public bool IsEquivalentTo(BagWithLock other)
{
lock (lockObject)
lock (other.lockObject)
return object.Equals(data, other.data);
}
}
The problem I am worried about here is that, because of the way that
IsEquivalentTo is implemented, I could be left with a deadlock condition,
if a thread invoked item1.IsEquivalentTo(item2) and acquired item1's lock,
and another invoked item2.IsEquivalentTo(item1) and acquired item2.
What should I do to ensure, as much as possible, that such deadlocks
cannot happen?
No comments:
Post a Comment