读写锁是进程同步中经常使用的锁。
在System.Core中ReaderWriterLockSlim类比较好用,它是基于写优先策略的。它还支持从读锁升级到写锁,称为Upgradable Mode.
简单测试代码如下:
private static void Test() { ReaderWriterLockSlim locker = new ReaderWriterLockSlim(); ParameterizedThreadStart reader = o => { var innerlocker = locker; int number = Convert.ToInt32(o); while (true) { locker.EnterReadLock(); Console.WriteLine("Reading " + number); Thread.Sleep(500); locker.ExitReadLock(); } }; ParameterizedThreadStart writer = o => { var innerlocker = locker; int number = Convert.ToInt32(o); while (true) { locker.EnterWriteLock(); Console.WriteLine("Writing " + number); Thread.Sleep(50); locker.ExitWriteLock(); } }; for (int i = 1; i <= 100; i++) { Thread thread = new Thread(reader); thread.Start(i); } for (int i = 11; i <= 15; i++) { Thread thread = new Thread(writer); thread.Start(i); } AutoResetEvent waitForever = new AutoResetEvent(false); waitForever.WaitOne(); }