读写锁ReaderWriterLockSlim
摘要
在读写锁中,多线程可以同时读取,只有在要写入时会被锁住(需读取线程结束时写入,此时堵塞其他线程请求)
EnterReadLock尝试进入写入模式锁定状态
EnterWriteLock 尝试进入写入模式锁定状态
TryEnterReadLock(Int32)尝试进入读取模式锁定状态,可以选择整数超时时间
TryEnterWriteLock(Int32) 尝试进入写入模式锁定状态,可以选择超时时间
ExitReadLock减少读取模式的递归计数,并在生成的计数为 0(零)时退出读取模式
ExitWriteLock 减少写入模式的递归计数,并在生成的计数为 0(零)时退出写入模式
PS
通过Interlocked对线程读写访问个数进行操作
public class ReaderWriterGuard
{
private readonly ReaderWriterLockSlim _readerWriterLockSlim = new ReaderWriterLockSlim();
private long _counter;
public void EnterReadLock()
{
Interlocked.Increment(ref _counter);
_readerWriterLockSlim.EnterReadLock();
}
public void EnterUpgradeableReadLock()
{
Interlocked.Increment(ref _counter);
_readerWriterLockSlim.EnterUpgradeableReadLock();
}
public void EnterWriteLock()
{
Interlocked.Increment(ref _counter);
_readerWriterLockSlim.EnterWriteLock();
}
public void ExitReadLock()
{
_readerWriterLockSlim.ExitReadLock();
Interlocked.Decrement(ref _counter);
}
public void ExitUpgradeableReadLock()
{
_readerWriterLockSlim.ExitUpgradeableReadLock();
Interlocked.Decrement(ref _counter);
}
public void ExitWriteLock()
{
_readerWriterLockSlim.ExitWriteLock();
Interlocked.Decrement(ref _counter);
}
public bool TryEnterReadLock(int millisecondsTimeout)
{
if (_readerWriterLockSlim.TryEnterReadLock(millisecondsTimeout))
{
Interlocked.Increment(ref _counter);
return true;
}
return false;
}
public bool TryEnterReadLock(TimeSpan timeout)
{
if (_readerWriterLockSlim.TryEnterReadLock(timeout))
{
Interlocked.Increment(ref _counter);
return true;
}
return false;
}
public bool TryEnterUpgradeableReadLock(int millisecondsTimeout)
{
if (_readerWriterLockSlim.TryEnterUpgradeableReadLock(millisecondsTimeout))
{
Interlocked.Increment(ref _counter);
return true;
}
return false;
}
public bool TryEnterUpgradeableReadLock(TimeSpan timeout)
{
if (_readerWriterLockSlim.TryEnterUpgradeableReadLock(timeout))
{
Interlocked.Increment(ref _counter);
return true;
}
return false;
}
public bool TryEnterWriteLock(int millisecondsTimeout)
{
if (_readerWriterLockSlim.TryEnterWriteLock(millisecondsTimeout))
{
Interlocked.Increment(ref _counter);
return true;
}
return false;
}
public bool TryEnterWriteLock(TimeSpan timeout)
{
if (_readerWriterLockSlim.TryEnterWriteLock(timeout))
{
Interlocked.Increment(ref _counter);
return true;
}
return false;
}
}
线程安全性的字典集 ConcurrentDictionary
//插入在上方
private static readonly ConcurrentDictionary<string, Lazy<ReaderWriterGuard>> Guards =
new ConcurrentDictionary<string, Lazy<ReaderWriterGuard>>();
//创建懒惰的本类对象
public static ReaderWriterGuard Take(string name)
{
return Guards
.GetOrAdd(name, k => new Lazy<ReaderWriterGuard>(() => new ReaderWriterGuard()))
.Value;
}
public static void Release(string name)
{
if (Guards.TryGetValue(name, out Lazy<ReaderWriterGuard> value))
{
if (Interlocked.Read(ref value.Value._counter) <= 0)
{
Guards.TryRemove(name, out Lazy<ReaderWriterGuard> _);
}
}
}
蹭的