操作 | 读取锁状态 | 写入锁状态 | 获取锁是否需要等待 |
---|---|---|---|
获取读取锁 | 未获取 | 未获取 | 无需等待 |
获取读取锁 | 已被其他线程获取 | 未获取 | 无需等待 |
获取读取锁 | 未获取 | 已被其他线程获取 | 需要等待其他线程释放 |
获取写入锁 | 未获取 | 未获取 | 无需等待 |
获取写入锁 | 已被其他线程获取 | 未获取 | 需要等待其他线程释放 |
获取写入锁 | 未获取 | 已被其他线程获取 | 需要等待其他线程释放 |
class Program
{
static void Main(string[] args)
{
var c = ReadWriteLockDemo.GetValue("value", x =>
{
Console.WriteLine(x);
return x;
});
Console.WriteLine("结束了");
Console.WriteLine($@"获取到的结果为:{c}");
}
}
public static class ReadWriteLockSimpleDemo
{
private static ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
private static int _countA = 0;
public static int _countB = 0;
/// <summary>
/// 增加
/// </summary>
public static void IncrementCounters()
{
_lock.EnterWriteLock();
try
{
++_countA;
++_countB;
}
finally
{
_lock.ExitWriteLock();
}
}
/// <summary>
/// 获取
/// </summary>
/// <param name="countA"></param>
/// <param name="countB"></param>
public static void GetCounters(ref int countA, ref int countB)
{
_lock.EnterReadLock();
try
{
countA = _countA;
countB = _countB;
}
finally
{
_lock.ExitReadLock();
}
}
}
public static class ReadWriteLockDemo
{
private static ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
private static Dictionary<string, string> _dict = new Dictionary<string, string>();
public static string GetValue(string key, Func<string, string> factory)
{
_lock.EnterUpgradeableReadLock();
try
{
//值已生成时可以直接返回
if (_dict.TryGetValue(key, out var value))
{
return value;
}
//获取(升级到)写入锁
_lock.EnterWriteLock();
try
{
//再次判断值是否已生成
if (!_dict.TryGetValue(key, out value))
{
value = factory(key);
_dict.Add(key, value);
}
return value;
}
finally
{
//释放写入锁
_lock.ExitWriteLock();
}
}
finally
{
//释放读取锁
_lock.ExitUpgradeableReadLock();
}
}
}
本文基于.Net Core底层入门总结内容
如有哪里讲得不是很明白或是有错误,欢迎指正
如您喜欢的话不妨点个赞收藏一下吧??
原文:https://www.cnblogs.com/ancold/p/14974309.html