使用ReaderWriterLock类实现多用户读/单用户写同步[1]
2015-03-12
应用程序在访问资源时是进行读操作,写操作相对较少。为解决这一问题,C#提供了System.Threading.ReaderWriterLock类以适应多用户读/单用户写的场景。
该类可实现以下功能:如果资源未被写操作锁定,那么任何线程都可对该资源进行读操作锁定,并且对读操作锁数量没有限制,即多个线程可同时对该资源进行读操作锁定,以读取数据。如果资源未被添加任何读或写操作锁,那么一个且仅有一个线程可对该资源添加写操作锁定,以写入数据。简单的讲就是:读操作锁是共享锁,允许多个线程同时读取数据;写操作锁是独占锁,同一时刻,仅允许一个线程进行写操作。
代码如下:
1 using System; 2 using System.Threading; 3 4 namespace ProcessTest 5 { 6 class Program 7 { 8 //读、写操作锁 9 static ReaderWriterLock rwl = new ReaderWriterLock();10 11 static void Main(string[] args)12 {13 //分别创建2个读操作线程,2个写操作线程,并启动14 Thread tr0 = new Thread(new ParameterizedThreadStart(Read));15 Thread tr1 = new Thread(new ParameterizedThreadStart(Read));16 Thread tr2 = new Thread(new ParameterizedThreadStart(Write));17 Thread tr3 = new Thread(new ParameterizedThreadStart(Write));18 19 tr0.Start("R0");20 tr1.Start("R1");21 tr2.Start("W2");22 tr3.Start("W3");23 24 //等待线程执行完毕25 tr0.Join();26 tr1.Join();27 tr2.Join();28 tr3.Join();29 30 System.Console.ReadKey();31 }32 33 //读数据34 static void Read(object state)35 {36 for (int i = 0; i < 3; i++)37 {38 try39 {40 //申请读操作锁,如果在1000ms内未获取读操作锁,则放弃41 rwl.AcquireReaderLock(1000);42 Console.WriteLine("Begin Read,Thread = {0}", state);43 Thread.Sleep(10);44 Console.WriteLine("End Read,Thread = {0}", state);45 //释放读操作锁46 rwl.ReleaseReaderLock();47 }48 catch (ApplicationException)49 {50 //获取读操作锁失败的处理51 }52 }53 }54 55 //写数据56 static void Write(object state)57 {58 for (int i = 0; i < 3; i++)59 {60 try61 {62 //申请写操作锁,如果在1000ms内未获取写操作锁,则放弃63 rwl.AcquireWriterLock(1000);64 Console.WriteLine("Begin write,Thread = {0}", state);65 Thread.Sleep(100);66 Console.WriteLine("End write,Thread = {0}", state);67 //释放写操作锁68 rwl.ReleaseWriterLock();69 }70 catch (ApplicationException)71 {72 //获取写操作锁失败73 }74 }75 }76 }77 }
结果如下:
参考:
[1]
[2]