读写锁一般用于高性能应用场景,.net 好像有内置读写锁,还没去看具体实现。我个人是以原子锁方式实现,主要用于并发读,独占写,并以写优先。关于优先的设计,应该有几种策略,就是读优先还是写优先还是均衡。我以写优先的原因在于,如果此时存在有待写入的数据,那么认为之前的数据已经过时,获取之前的数据将没有任何意义。不过缺陷在于高并发读频繁写的场景下,可能会导致大量读取等待,一直写。个人认为不同的策略各具优势和缺陷,应贴合业务实际做设计,代码具有很高程度的可优化性,具体性能还不知道怎么样,有兴趣的可以测测。
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Common
{
public class ReadWriteLock
{
private int _writeMonopoly = 0;
private int _counter = 0;
private bool _canRead=true;
public void ExecRead(Action a)
{
while (true)
{
bool success = false;
Interlocked.Increment(ref _counter);
if (_canRead)
{
a();
success = true;
}
Interlocked.Decrement(ref _counter);
if (success)
{
break;
}
while (!_canRead)
{
Thread.Sleep(1);
}
}
}
public void ExecWrite(Action a)
{
while(Interlocked.CompareExchange(ref _writeMonopoly, 1, 0) == 1)
{
Thread.Sleep(1);
}
_canRead = false;
while (_counter > 0)
{
Thread.Sleep(1);
}
a();
_canRead = true;
Interlocked.Exchange(ref _writeMonopoly, 0);
}
}
}