我有一个简单的类,我想使它线程安全。该类需要实现IComparer。我知道以线程安全的方式实施int CompareTo(T other)
并不是直截了当的。如果我不以正确的方式锁定,那么容易造成死锁。我有三个问题:这是如何编写线程安全IComparable?
- 此代码是否线程安全?如果不是,我该如何解决?
- 此代码可以缩短吗?它看起来像一个简单的减法很多代码。
- 我应该甚至打扰
int CompareTo(T other)
线程安全吗?我是否应该要求调用者(通常是排序)锁定所有相关的BObject?
这里是我的代码:
public class BObject : IComparable<BObject>
{
//Each BObject has a unique object id
private static int _bObjectId = 0;
private static int GetNextId()
{
return System.Threading.Interlocked.Increment(ref BObject._bObjectId);
}
private object _locker = new object();
private readonly int _id = BObject.GetNextId();
//Some variable
private int _sales;
public int Sales
{
get
{
lock (this._locker)
return this._sales;
}
set
{
lock (this._locker)
this._sales = value;
}
}
public int CompareTo(BObject other)
{
int result;
//Can I simply do "if (this._id == other._id)"
if (object.ReferenceEquals(this, other))
result = 0;
else
{
//get the BObject with the lower id
BObject lower = this._id < other._id ? this : other;
//get the BObject with the higher id
BObject higher = this._id > other._id ? this : other;
//lock the BObject with the lower id first
lock (lower._locker)
{
//lock the BObject with the higher id last
lock (higher._locker)
{
//put object with lower Sales first
result = this.Sales - other.Sales;
}
}
}
return result;
}
}
锁定每个成员不会使您的代码线程安全。 – SLaks
特别是,'int's已经是原子的;你根本不需要锁。 – SLaks
使比较线程安全的最简单方法:使您的类型不可变。 –