zoukankan      html  css  js  c++  java
  • 线程同步: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();
    }
  • 相关阅读:
    NOIP simulation
    NOIP2013
    BZOJ 4176 Lucas的数论
    BZOJ 3512 DZY Loves Math IV
    BZOJ 3994 Sum
    BZOJ 4174 tty的求助
    BZOJ 3561 DZY Loves Math VI
    BZOJ 2508 简单题/BZOJ 3775 点和直线
    FTR #1 百步穿杨
    BZOJ 4407 于神之怒加强版
  • 原文地址:https://www.cnblogs.com/zgynhqf/p/1624940.html
Copyright © 2011-2022 走看看