首页 > 编程语言 >C# 锁

C# 锁

时间:2023-07-24 11:33:48浏览次数:31  
标签:C# int 单循环 线程 outerLoopCount stopwatch ThreadNum

代码

using System.Diagnostics;

namespace ConsoleAppLockDemo
{
    internal  class Program
    {
        static object lockobj = new object();
        static ReaderWriterLockSlim readerWriterLock = new ReaderWriterLockSlim();


        static async Task Main(string[] args)
        {


            //外循环数量
            int outerLoopCount = 1 ;
            //线程数量
            int ThreadNum = 100000;

            Stopwatch stopwatch = new Stopwatch(); 
            ///1原子锁
            int islock = 0;
            int countInterlocked = 0;
            stopwatch.Restart();
            for (int j = 0; j < outerLoopCount; j++)
            {
                for (int i = 0; i < ThreadNum; i++)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        while (Interlocked.CompareExchange(ref islock, 1, 0) == 1)
                        {


                        }
                        countInterlocked = countInterlocked + 2;
                        Interlocked.Exchange(ref islock, 0);
                    });

                }
            }
         
            stopwatch.Stop();

            Console.WriteLine($">>Interlocked.Exchange\t外循环数量:{outerLoopCount},线程数量:{ThreadNum},执行时间:{stopwatch.ElapsedMilliseconds} ms,单循环{ThreadNum}线程: 执行速度:{stopwatch.ElapsedMilliseconds*1.0/ outerLoopCount} ms/单循环");
            //2临界锁
          
     
            int countlockobj = 0;

            stopwatch.Restart();
            for (int j = 0; j < outerLoopCount; j++)
            {
                for (int i = 0; i < ThreadNum; i++)
                {
                    await Task.Factory.StartNew(() =>
                    {

                        lock (lockobj)
                        {

                            countlockobj = countlockobj + 2;
                        }
                    });

                }
            }
            stopwatch.Stop();

            Console.WriteLine($">>lock\t\t\t外循环数量:{outerLoopCount},线程数量:{ThreadNum},执行时间:{stopwatch.ElapsedMilliseconds} ms,单循环{ThreadNum}线程: 执行速度:{stopwatch.ElapsedMilliseconds * 1.0 / outerLoopCount} ms/单循环");

            int InterlockedCount = 0;

            //3原子性操作
            stopwatch.Restart();
            for (int j = 0; j < outerLoopCount; j++)
            {
                for (int i = 0; i < ThreadNum; i++)
                {
                    await Task.Factory.StartNew(() =>
                    {



                        Interlocked.Add(ref InterlockedCount, 2);

                    });

                }
            }
            stopwatch.Stop();

            int InterlockedCount2 = 0;
            Console.WriteLine($">>Interlocked Add\t外循环数量:{outerLoopCount},线程数量:{ThreadNum},执行时间:{stopwatch.ElapsedMilliseconds} ms,单循环{ThreadNum}线程: 执行速度:{stopwatch.ElapsedMilliseconds * 1.0 / outerLoopCount} ms/单循环");
            stopwatch.Restart();
            for (int j = 0; j < outerLoopCount; j++) 
            {
                for (int i = 0; i < ThreadNum; i++)
                {
                    await Task.Factory.StartNew(() =>
                    {



                        Interlocked.Increment(ref InterlockedCount2);

                    });

                }
            }
               
            stopwatch.Stop();
            Console.WriteLine($">>Interlocked Increment\t外循环数量:{outerLoopCount},线程数量:{ThreadNum},执行时间:{stopwatch.ElapsedMilliseconds} ms,单循环{ThreadNum}线程: 执行速度:{stopwatch.ElapsedMilliseconds * 1.0 / outerLoopCount} ms/单循环");
            //4 读写锁
     
            int ReaderWriterLockCount  = 0;

            stopwatch.Restart();
            for (int j = 0; j < outerLoopCount; j++)
            {

                for (int i = 0; i < ThreadNum; i++)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        readerWriterLock.EnterWriteLock();


                        ReaderWriterLockCount = ReaderWriterLockCount + 2;
                        readerWriterLock.ExitWriteLock();
                    });

                }
            }
              

            stopwatch.Stop();
            Console.WriteLine($">>ReaderWriterLockSlim\t外循环数量:{outerLoopCount},线程数量:{ThreadNum},执行时间:{stopwatch.ElapsedMilliseconds} ms,单循环{ThreadNum}线程: 执行速度:{stopwatch.ElapsedMilliseconds * 1.0 / outerLoopCount} ms/单循环");
            int ReaderWriterLockCount3 = 0;
        
            ///
            ReaderWriterLock readerWriterLock3 = new ReaderWriterLock();
            stopwatch.Restart();
            for (int j = 0; j < outerLoopCount; j++)
            {
                for (int i = 0; i < ThreadNum; i++)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        readerWriterLock3.AcquireWriterLock(2000);


                        ReaderWriterLockCount3 = ReaderWriterLockCount3 + 2;
                        readerWriterLock3.ReleaseWriterLock();
                    });

                }

            }
         

            stopwatch.Stop();
            Console.WriteLine($">>ReaderWriterLock\t外循环数量:{outerLoopCount},线程数量:{ThreadNum},执行时间:{stopwatch.ElapsedMilliseconds} ms,单循环{ThreadNum}线程: 执行速度:{stopwatch.ElapsedMilliseconds * 1.0 / outerLoopCount} ms/单循环");

            //5信号量
         
            Semaphore semaphore=new Semaphore(1,1);
            int SemaphoreCount  = 0;
            stopwatch.Restart();
            for (int j = 0; j < outerLoopCount; j++)
            {

                for (int i = 0; i < ThreadNum; i++)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        semaphore.WaitOne();


                        SemaphoreCount = SemaphoreCount + 2;
                        semaphore.Release();
                    });

                }
            }
            
            stopwatch.Stop();
            Console.WriteLine($">>Semaphore\t\t外循环数量:{outerLoopCount},线程数量:{ThreadNum},执行时间:{stopwatch.ElapsedMilliseconds} ms,单循环{ThreadNum}线程: 执行速度:{stopwatch.ElapsedMilliseconds * 1.0 / outerLoopCount} ms/单循环");

            SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1 );
            int semaphoreSlimCount = 0;
            stopwatch.Restart();
            for (int j = 0; j < outerLoopCount; j++)
            {
                for (int i = 0; i < ThreadNum; i++)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        semaphoreSlim.Wait();
                        //or
                        //semaphoreSlim.Wait(2000);

                        semaphoreSlimCount = semaphoreSlimCount + 2;
                        semaphoreSlim.Release();
                    });

                }
            }
               
            stopwatch.Stop();
            Console.WriteLine($">>SemaphoreSlim\t\t外循环数量:{outerLoopCount},线程数量:{ThreadNum},执行时间:{stopwatch.ElapsedMilliseconds} ms,单循环{ThreadNum}线程: 执行速度:{stopwatch.ElapsedMilliseconds * 1.0 / outerLoopCount} ms/单循环");

            //6 事件 
            //初始化为true
            AutoResetEvent autoResetEvent = new AutoResetEvent( true );
          
            int autoResetEventCount = 0;
            stopwatch.Restart();

            for (int j = 0; j < outerLoopCount; j++)
            {
                for (int i = 0; i < ThreadNum; i++)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        autoResetEvent.WaitOne();
                        //or
                        //autoResetEvent.WaitOne(2000 );


                        autoResetEventCount = autoResetEventCount + 2;
                        autoResetEvent.Set();
                    });

                }
            }
            
            stopwatch.Stop();
            Console.WriteLine($">>AutoResetEvent\t外循环数量:{outerLoopCount},线程数量:{ThreadNum},执行时间:{stopwatch.ElapsedMilliseconds} ms,单循环{ThreadNum}线程: 执行速度:{stopwatch.ElapsedMilliseconds * 1.0 / outerLoopCount} ms/单循环");
            //阻塞线程
            autoResetEvent.Reset();

            ManualResetEvent manualResetEvent = new ManualResetEvent(true);

            int manualResetEventCount = 0;
            stopwatch.Restart();
            for (int j = 0; j < outerLoopCount; j++)
            {
                for (int i = 0; i < ThreadNum; i++)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        manualResetEvent.WaitOne();
                        manualResetEventCount = manualResetEventCount + 2;
                        manualResetEvent.Set();
                    });

                }
            }
               
            stopwatch.Stop();
            Console.WriteLine($">>ManualResetEvent\t外循环数量:{outerLoopCount},线程数量:{ThreadNum},执行时间:{stopwatch.ElapsedMilliseconds} ms,单循环{ThreadNum}线程: 执行速度:{stopwatch.ElapsedMilliseconds * 1.0 / outerLoopCount} ms/单循环");
            manualResetEvent.Reset();


            ManualResetEventSlim manualResetEventSlim = new ManualResetEventSlim(true);

            int manualResetEventSlimCount = 0;

            stopwatch.Restart();
            for (int j = 0; j < outerLoopCount; j++)
            {
                for (int i = 0; i < ThreadNum; i++)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        manualResetEventSlim.Wait();



                        manualResetEventSlimCount = manualResetEventSlimCount + 2;
                        manualResetEventSlim.Set();
                    });

                }
            }
          
            stopwatch.Stop();
            Console.WriteLine($">>ManualResetEventSlim\t外循环数量:{outerLoopCount},线程数量:{ThreadNum},执行时间:{stopwatch.ElapsedMilliseconds} ms,单循环{ThreadNum}线程: 执行速度:{stopwatch.ElapsedMilliseconds * 1.0 / outerLoopCount} ms/单循环");
            manualResetEventSlim.Reset();
            //7互斥

            Mutex mutex = new Mutex();
            int mutexCount = 0;
            stopwatch.Restart();
            for (int j = 0; j < outerLoopCount; j++)
            {
                for (int i = 0; i < ThreadNum; i++)
                {
                    await Task.Factory.StartNew(() =>
                    {
                        mutex.WaitOne();



                        mutexCount = mutexCount + 2;
                        mutex.ReleaseMutex();
                    });

                }
            }
            stopwatch.Stop();
            Console.WriteLine($">>Mutex\t\t\t外循环数量:{outerLoopCount},线程数量:{ThreadNum},执行时间:{stopwatch.ElapsedMilliseconds} ms,单循环{ThreadNum}线程: 执行速度:{stopwatch.ElapsedMilliseconds * 1.0 / outerLoopCount} ms/单循环");
            Console.ReadLine();
        }
    }
}

10000线程测试结果

 10000线程测试结果

 1000线程测试结果

 

标签:C#,int,单循环,线程,outerLoopCount,stopwatch,ThreadNum
From: https://www.cnblogs.com/JohnnyLei/p/17576807.html

相关文章

  • 在Centos7安装Mongodb
    背景为了创建一个关于nodejs项目,选取mongodb作为数据库使用。WindowsC盘还剩1GB,于是决定装到Centos7服务器上。安装下载安装包:https://www.mongodb.com/try/download/community-kubernetes-operator拖拽安装包:解压缩:tar-zxvfmongodb-linux-x86_64-rhel70-6.0.8.tgz......
  • 泛型和Object的区别
    什么时候使用泛型:只要确定了用哪类对象,并且用到这个对象里的方法。选择泛型,泛型更加精确,只要用到Object的地方基本都能用泛型代替。Object类:Object是所有类的父类,更加笼统,且只能使用固定的属性。例:将List<Object>aa转化List<QueryBO>bb。@DatapublicclassQueryBO{......
  • 比AD更好用的“PCB设计文件转生产文件”工具
    问:为何要将PCB文件转换为GERBER文件和钻孔数据?答:因为GERBER文件是一种国际标准的光绘格式文件,它包含RS-274-D和RS-274-X两种格式,其中RS-274-D称为基本GERBER格式,并要同时附带D码文件才能完整描述一张图形;RS-274-X称为扩展GERBER格式,它本身包含有D码信息,常用的EDA软件都能生成此二......
  • Python【17】 torch.cat()
    竖着或者横着拼接矩阵参考:https://www.cnblogs.com/JeasonIsCoding/p/10162356.html参考:https://blog.csdn.net/qian2213762498/article/details/88795848......
  • kibana security 权限 分配
    kibanasecurity权限分配1.创建users设置密码,role随便选一个,后面要改成customerrole。2.创建roles主要是elastcisearch这个大页里面Clusterprivileges留白。RunAsprivileges选第一步里面的用户。indexprivileges选择所需的indices,然后privileges选择read,......
  • 记录windows、vs2019、c++、cuda环境配置
    原文链接:   (45条消息)CUDA+Windows+VS环境配置_cudavs_哈哈哈哈哈嗝哈哈哈的博客-CSDN博客            VS2019--c++CUDA环境配置与编程实例-知乎(zhihu.com)测试代码:.cu文件中:#include"stdio.h"#include<cuda_runtime.h>#include<devi......
  • python的lru_cache
    functools模块中的lru_cache是一个装饰器,用于缓存函数的结果,以避免重复计算。LRU(LeastRecentlyUsed)表示最近最少使用,这意味着当缓存空间满时,会优先删除最久未被使用的缓存项。要使用lru_cache装饰器,需要将其应用于你想要缓存的函数。以下是一个简单的例子:importfunctools@f......
  • 如何从 Fedora 37 工作站升级到 Fedora 38(GUI 和 CLI)
    导读使用GUI和CLI方法从Fedora37工作站版升级到Fedora38的完整步骤。Fedora38已发布,没有任何延误。此版本带来了令人惊叹的GNOME44工作站版桌面、KDEPlasma5.27(最后一个Plasma5系列)等。你可以在此页面上阅读我写的Fedora38功能指南。如果你尝......
  • easyui combobox 多选及全选 功能(XTHS_实测可行)
    代码如下:$("#DepartmentCode").comboex({data:[{"value":"","text":"全部"},{"value":"001","text":"部门1"},{......
  • JavaScript复习知识点
    原型在JavaScript中,每个对象都有一个原型(prototype)。原型是一个对象,其他对象可以通过它来继承属性和方法。简单来说,对象通过其原型来共享和访问属性和方法。原型以原型链的形式连接在一起,形成了一个对象和原型之间的关系。当我们访问对象的属性或方法时,JavaScript引擎首先在......