【发布时间】:2008-12-20 15:32:33
【问题描述】:
如果我使用ReaderWriterLockSlim 来获取读/写锁,我需要将我的变量设为volatile 还是使用Interlocked.Increment?
例如,下面Add 方法中的代码是否可以正常工作,还是需要增强?
public class AppendableList<T> { // semi-immutable; supports appending only
private T[] data = new T[16];
private ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim();
public int Count { get; private set; }
public T this[int index] {
get {
rwLock.EnterReadLock();
try { return data[index]; } finally { rwLock.ExitReadLock(); }
}
}
public void Add(T item) {
rwLock.EnterUpgradeableReadLock();
try {
if (Count == data.Length)
reAllocateArray(); // upgrades to write lock
data[Count++] = item; // do I need to use Interlocked here?
} finally { rwLock.ExitUpgradeableReadLock(); }
}
}
编辑:我正在尝试编写一个轻量级、快速且简单的列表,允许多个线程同时访问其数据(类似于生产者-消费者缓冲区)。我已经编辑了上面的代码,删除了我之前使用的简化,所以现在问题应该更清楚了。在我看来,这段代码是线程安全的,但我不确定是否所有线程都会在退出可升级锁后立即看到 Count 的更新值。
EDIT 2:这里的“Write”锁用于指示写入数组引用,而不是数组元素。我假设这已经足够了(因为数据本身是不可变的)。我想我需要在递增Count 时使用 Interlocked。这是真的吗?
【问题讨论】:
-
Jeffrey Richter's article 提供了一些关于 ReaderWriterLock 的详细建议。
-
这篇文章提供了更多关于 ReaderWriterLockSlim 的信息:bluebytesoftware.com/blog/2007/02/07/…
标签: .net multithreading locking