读写锁学习(1)——ReaderWriterLock学习

读写锁的目的:将读和写分离,可以实现多个用户的读操作,但是写操作只能有一个用户执行。

实例:

using System;
using System.Threading;

namespace ProcessTest
{
    class Program
    {
        static int theResource = 0;
        static ReaderWriterLock rwl = new ReaderWriterLock();

        static void Main(string[] args)
        {
            //分别创建2个读操作线程,2个写操作线程,并启动
            Thread tr0 = new Thread(new ThreadStart(Read));
            Thread tr1 = new Thread(new ThreadStart(Read));
            Thread tr2 = new Thread(new ThreadStart(Write));
            Thread tr3 = new Thread(new ThreadStart(Write));

            tr0.Start();
            tr1.Start();
            tr2.Start();
            tr3.Start();

            ////等待线程执行完毕
            //tr0.Join();
            //tr1.Join();
            //tr2.Join();
            //tr3.Join();

            System.Console.ReadKey();
        }

        //读数据
        static void Read()
        {
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    //申请读操作锁,如果在1000ms内未获取读操作锁,则放弃
                    rwl.AcquireReaderLock(1000);
                    Console.WriteLine("开始读取数据,theResource = {0}", theResource);
                    Thread.Sleep(10);
                    Console.WriteLine("读取数据结束,theResource = {0}", theResource);
                    //释放读操作锁
                    rwl.ReleaseReaderLock();
                }
                catch (ApplicationException)
                {
                    Console.WriteLine("读数据失败");
                }
            }
        }

        //写数据
        static void Write()
        {
            for (int i = 0; i < 3; i++)
            {
                try
                {
                    //申请写操作锁,如果在1000ms内未获取写操作锁,则放弃
                    rwl.AcquireWriterLock(1000);
                    Console.WriteLine("开始写数据,theResource = {0}", theResource);
                    //将theResource加1
                    theResource++;
                    Thread.Sleep(100);
                    Console.WriteLine("写数据结束,theResource = {0}", theResource);
                    //释放写操作锁
                    rwl.ReleaseWriterLock();
                }
                catch (ApplicationException)
                {
                    Console.WriteLine("写数据失败");
                }
            }
        }
    }
}
原文地址:https://www.cnblogs.com/Freedom0619/p/4113413.html