一、简介
当我们需要对一个共享资源多次读取的时候,用前面Monitor的同步锁就没有必要了。因为同步锁每次只允许一个线程访问共享资源,其他线程都会阻塞。
此时,通过ReaderWriterLock类可以很好的实现读取并行。
二、例子
1 using System; 2 using System.Threading; 3 4 namespace ThreadMonitor 5 { 6 class Program 7 { 8 private static object lockObj = new object(); 9 private static ReaderWriterLock readerwritelock = new ReaderWriterLock(); 10 static void Main(string[] args) 11 { 12 for (int i = 0; i < 10; i++) 13 { 14 Thread testthread = new Thread(Add); 15 testthread.IsBackground = true; 16 testthread.Start(); 17 } 18 19 for (int i = 0; i < 10; i++) 20 { 21 Thread testthread2 = new Thread(Read); 22 testthread2.IsBackground = true; 23 testthread2.Start(); 24 } 25 Console.WriteLine("All thread created done!"); 26 Console.Read(); 27 } 28 29 // 共享资源 30 public static int number = 1; 31 32 public static void Add() 33 { 34 //Monitor.Enter(lockObj); //获得排他锁,每次只有一个线程可以进入 35 readerwritelock.AcquireWriterLock(50000); 36 Console.ForegroundColor = ConsoleColor.DarkGreen; 37 Console.WriteLine($"{DateTime.Now} CurrentThreadIDAdd:{Thread.CurrentThread.ManagedThreadId} CurrentValue:{number++}" ); 38 Thread.Sleep(2000); 39 Console.ResetColor(); 40 //Monitor.Exit(lockObj); 41 readerwritelock.ReleaseWriterLock(); 42 43 } 44 public static void Read() 45 { 46 //Monitor.Enter(lockObj); //获得排他锁 47 readerwritelock.AcquireReaderLock(50000); 48 Console.ForegroundColor = ConsoleColor.DarkRed; 49 Console.WriteLine($"{DateTime.Now} CurrentThreadIDRead:{Thread.CurrentThread.ManagedThreadId} CurrentValue:{number}"); 50 Thread.Sleep(2000); 51 Console.ResetColor(); 52 readerwritelock.ReleaseReaderLock(); 53 //Monitor.Exit(lockObj);// 释放指定对象上的排他锁。 54 55 } 56 } 57 }
运行结果如下: