假设我有以下类:
public class IntBagWithLock
{
private readonly lockObject = new object();
private bool assigned = false;
private int data1;
private int data2;
public int? Data1
{
get { lock (lockObject) { return assigned ? data1 : (int?)null; } }
}
public int? Data2
{
get { lock (lockObject) { return assigned ? data2 : (int?)null; } }
}
public bool Assigned { get { lock(lockObject) { return assigned; } }
public bool TrySetData(int value1, int value2)
{
lock (lockObject)
{
if (assigned) return false;
data1 = value1;
data2 = value2;
assigned = true;
return true;
}
}
public bool IsEquivalentTo(IntBagWithLock other)
{
if (ReferenceEquals(this, other)) return true;
if (ReferenceEquals(other, null)) return false;
lock (lockObject)
{
if (!assigned) return false;
lock (other.lockObject)
{
return other.assigned && other.data1 == data1 && other.data2 == data2;
}
}
}
}
我担心的问题是,由于
IsEquivalentTo
的实现方式,如果一个线程调用item1.IsEquivalentTo(item2)
并获取了item1
的锁,另一个线程调用item2.IsEquivalentTo(item1)
并获取了item2
的锁,就会导致死锁的情况。为了尽可能避免这种死锁的发生,应该怎么做呢? 更新2:代码示例已经修改成更接近我的实际情况了。我认为所有的答案仍然有效。
IntBagWithLock
只能通过构造函数进行初始化?这样就可以摆脱锁定。 - Sriram Sakthivel