• 多线程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();
                    }
                }
            }
        }
  • 相关阅读:
    IIS配置(持续更新中...)
    T-SQL Table-valued Function使用分隔符将字符串转换为表
    英语中的时态
    网页内容扫描器
    20145223 杨梦云 《网络对抗》 Web安全基础实践
    20145223 杨梦云 《网络对抗》 Web基础
    20145223 杨梦云 《网络对抗》 网络欺诈技术防范
    20145223 杨梦云 《网络对抗》 信息搜集与漏洞扫描
    20145223 杨梦云 《网络对抗》 MSF基础应用
    20145223 杨梦云 《网络对抗》恶意代码分析
  • 原文地址:https://www.cnblogs.com/shidengyun/p/5608115.html
Copyright © 2020-2023  润新知