码迷,mamicode.com
首页 > 编程语言 > 详细

多线程15-ReaderWriterLockSlim

时间:2016-06-22 18:55:04      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

    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

标签:

原文地址:http://www.cnblogs.com/shidengyun/p/5608115.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!