多线程15-ReaderWriterLockSlim

Posted shidengyun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程15-ReaderWriterLockSlim相关的知识,希望对你有一定的参考价值。

    class Program
    {
        static void Main()
        {
            new Thread(Read) { IsBackground = true }.Start();
            new Thread(Read) { IsBackground = true }.Start();
            new Thread(Read) { IsBackground = true }.Start();
            new Thread(Read) { IsBackground = true }.Start();
            new Thread(Read) { IsBackground = true }.Start();
            new Thread(() => Write("T1")) { IsBackground = true }.Start();
            new Thread(() => Write("T2")) { IsBackground = true }.Start();
            Thread.Sleep(TimeSpan.FromSeconds(30));
        }
        static ReaderWriterLockSlim rwl = new ReaderWriterLockSlim();
        static Dictionary<intint> items = new Dictionary<intint>();
        static void Read()
        {
            Console.WriteLine("Readind contents of a dictionary");
            while (true)
            {
                try
                {
                    rwl.EnterReadLock();
                    foreach (var item in items.Keys)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(0.1));
                        Console.WriteLine(items[item]);
                    }
                }
                finally
                {
                    rwl.ExitReadLock();
                }
            }
        }
        static void Write(string threadName)
        {
            while (true)
            {
                try
                {
                    int newKey = new Random().Next(250);
                    rwl.EnterUpgradeableReadLock();
                    if (!items.ContainsKey(newKey))
                    {
                        try
                        {
                            rwl.EnterWriteLock();
                            items[newKey] = newKey;
                            Console.WriteLine("New Key {0} is added to a dictionary by a {1}", newKey, threadName);
                        }
                        finally
                        {
                            rwl.ExitWriteLock();
                        }
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(0.1));
                }
                finally
                {
                    rwl.ExitUpgradeableReadLock();
                }
            }
        }
    }

以上是关于多线程15-ReaderWriterLockSlim的主要内容,如果未能解决你的问题,请参考以下文章

什么是多线程,多进程?

多线程和多进程模式有啥区别

多线程Java多线程学习笔记 | 多线程基础知识

java中啥叫做线程?啥叫多线程?多线程的特点是啥

c++ 多线程与c多线程有啥区别?

IOS多线程安全(线程锁)