• 线程同步:System.Core中新的读写锁


    读写锁是进程同步中经常使用的锁。

    在System.Core中ReaderWriterLockSlim类比较好用,它是基于写优先策略的。它还支持从读锁升级到写锁,称为Upgradable Mode.

    简单测试代码如下:

    private static void Test()
    {
        ReaderWriterLockSlim locker = new ReaderWriterLockSlim();
        ParameterizedThreadStart reader = o =>
        {
            var innerlocker = locker;
            int number = Convert.ToInt32(o);
            while (true)
            {
                locker.EnterReadLock();
                Console.WriteLine("Reading  " + number);
                Thread.Sleep(500);
                locker.ExitReadLock();
            }
        };
        ParameterizedThreadStart writer = o =>
        {
            var innerlocker = locker;
            int number = Convert.ToInt32(o);
            while (true)
            {
                locker.EnterWriteLock();
                Console.WriteLine("Writing  " + number);
                Thread.Sleep(50);
                locker.ExitWriteLock();
            }
        };
        for (int i = 1; i <= 100; i++)
        {
            Thread thread = new Thread(reader);
            thread.Start(i);
        }
        for (int i = 11; i <= 15; i++)
        {
            Thread thread = new Thread(writer);
            thread.Start(i);
        }
    
        AutoResetEvent waitForever = new AutoResetEvent(false);
        waitForever.WaitOne();
    }
  • 相关阅读:
    数据库作业
    数据库知识点⑤
    数据库知识点④
    一个值得纪念的日子
    设计模式之单件模式
    HDU 5441 Travel
    HDU 5483 Nux Walpurgis
    Markdown 测试
    HDU 3271 SNIBB
    HDU 5536 Chip Factory
  • 原文地址:https://www.cnblogs.com/zgynhqf/p/1624940.html
Copyright © 2020-2023  润新知