首页 > 编程语言 >c# 多线程环境下控制对共享资源访问的办法

c# 多线程环境下控制对共享资源访问的办法

时间:2024-07-29 16:56:10浏览次数:8  
标签:Console c# void counter 共享资源 static IncrementCounter new 多线程

  1. Monitor:
    • 定义:Monitor 是 C# 中最基本的同步机制,通过 Enter 和 Exit 方法来控制对共享资源的访问。它提供了排他锁的功能,确保在任何时刻只有一个线程可以访问共享资源。
    • 优点:简单易用,适合对临界区进行粗粒度的同步控制。
    • 缺点:只能实现排它锁,不能实现读写锁,性能相对较低。

  

class Program
{
    static readonly object _lock = new object();
    static int _counter = 0;

    static void Main()
    {
        for (int i = 0; i < 10; i++)
        {
            new Thread(IncrementCounter).Start();
        }

        Console.ReadKey();
    }

    static void IncrementCounter()
    {
        Monitor.Enter(_lock);
        try
        {
            _counter++;
            Console.WriteLine($"Counter: {_counter}");
        }
        finally
        {
            Monitor.Exit(_lock);
        }
    }
}
Monitor

 

  1. Mutex:
    • 定义:Mutex 是一个操作系统对象,用于在进程间共享,通过 WaitOne 和 ReleaseMutex 来控制对共享资源的访问。它提供了进程间的同步能力。
    • 优点:可跨进程使用,适合在进程间进行同步。
    • 缺点:相比 Monitor,性能开销较大,因为涉及到系统调用。

  

class Program
{
    static Mutex _mutex = new Mutex();
    static int _counter = 0;

    static void Main()
    {
        for (int i = 0; i < 10; i++)
        {
            new Thread(IncrementCounter).Start();
        }

        Console.ReadKey();
    }

    static void IncrementCounter()
    {
        _mutex.WaitOne();
        _counter++;
        Console.WriteLine($"Counter: {_counter}");
        _mutex.ReleaseMutex();
    }
}
Mutex

 

  1. ReaderWriterLockSlim:
    • 定义:ReaderWriterLockSlim 实现了读写分离锁,允许多个线程同时读取共享资源,但只允许一个线程写入共享资源。这种机制适用于读多写少的场景。
    • 优点:适合读多写少的场景,提高了并发性能。
    • 缺点:相对复杂,可能会引起死锁,不支持递归锁。

  

class Program
{
    static ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();
    static int _counter = 0;

    static void Main()
    {
        for (int i = 0; i < 5; i++)
        {
            new Thread(ReadCounter).Start();
            new Thread(IncrementCounter).Start();
        }

        Console.ReadKey();
    }

    static void ReadCounter()
    {
        _rwLock.EnterReadLock();
        Console.WriteLine($"Counter: {_counter}");
        _rwLock.ExitReadLock();
    }

    static void IncrementCounter()
    {
        _rwLock.EnterWriteLock();
        _counter++;
        Console.WriteLine($"Counter incremented to: {_counter}");
        _rwLock.ExitWriteLock();
    }
}
ReaderWriterLockSlim

 

  1. Semaphore:
    • 定义:Semaphore 是一个信号量,用于控制同时访问共享资源的线程数量。通过 WaitOne 和 Release 方法,可以控制访问资源的线程数量。
    • 优点:可以控制多个线程同时访问共享资源的数量,灵活性较高。
    • 缺点:相对于其他机制,使用起来较为复杂,需要谨慎处理信号量的释放。

  

class Program
{
    static Semaphore _semaphore = new Semaphore(2, 2); // Allow 2 threads to access the resource simultaneously
    static int _counter = 0;

    static void Main()
    {
        for (int i = 0; i < 5; i++)
        {
            new Thread(IncrementCounter).Start();
        }

        Console.ReadKey();
    }

    static void IncrementCounter()
    {
        _semaphore.WaitOne();
        _counter++;
        Console.WriteLine($"Counter: {_counter}");
        _semaphore.Release();
    }
}
Semaphore

 

  1. SemaphoreSlim:
    • 定义:SemaphoreSlim 是轻量级的信号量,与 Semaphore 类似,用于控制同时访问共享资源的线程数量,但相比 Semaphore 更轻量级。
    • 优点:相比 SemaphoreSemaphoreSlim 的开销更小,适用于资源访问频繁的场景。
    • 缺点:与 Semaphore 相比,功能上略有限制,例如没有 Release(Int32) 方法,只能递增信号量一个单位。
class Program
{
    static SemaphoreSlim _semaphore = new SemaphoreSlim(2, 2); // Allow 2 threads to access the resource simultaneously
    static int _counter = 0;

    static void Main()
    {
        for (int i = 0; i < 5; i++)
        {
            new Thread(IncrementCounter).Start();
        }

        Console.ReadKey();
    }

    static void IncrementCounter()
    {
        _semaphore.Wait();
        _counter++;
        Console.WriteLine($"Counter: {_counter}");
        _semaphore.Release();
    }
}
SemaphoreSlim

 

  1. lock:
    • 定义:lock 是 C# 中的关键字,用于在代码块级别实现互斥锁,保护共享资源不被多个线程同时访问。
    • 优点:简单易用,适合对临界区进行细粒度的同步控制,编写起来比较方便。
    • 缺点:只能用于单线程内部的同步,不能跨越线程或进程,如果不小心使用会导致死锁。
class Program
{
    static readonly object _lock = new object();
    static int _counter = 0;

    static void Main()
    {
        for (int i = 0; i < 5; i++)
        {
            new Thread(IncrementCounter).Start();
        }

        Console.ReadKey();
    }

    static void IncrementCounter()
    {
        lock (_lock)
        {
            _counter++;
            Console.WriteLine($"Counter: {_counter}");
        }
    }
}
lock

 

标签:Console,c#,void,counter,共享资源,static,IncrementCounter,new,多线程
From: https://www.cnblogs.com/INetIMVC/p/18330485

相关文章

  • [米联客-安路飞龙DR1-FPSOC] FPGA基础篇连载-20 读写I2C接口的RTC时钟芯片
    软件版本:Anlogic-TD5.9.1-DR1_ES1.1操作系统:WIN1064bit硬件平台:适用安路(Anlogic)FPGA实验平台:米联客-MLK-L1-CZ06-DR1M90G开发板板卡获取平台:https://milianke.tmall.com/登录"米联客"FPGA社区http://www.uisrc.com视频课程、答疑解惑! 1概述    本节课继续利用I......
  • 【HarmonyOS】使用两层Scroll实现一天时间轴和事件卡片的层叠显示
    简介实现某一天24小时的时间长度和当天事件的页面。实现如下的效果:代码代码架构List_Page:主界面NumberUtil:数字辅助类DateEvenModel:日程实体类ListPageViewModel:界面交互类List_Pageimport{DateEvenModel}from'../Models/DateEvenModel';import{ListPageVie......
  • CNC turning and milling machine that can be used as a lathe and a milling machin
    ThecurrentCNCturningandmillingmachinetoolsaremainlymanifestedin2differenttypes,oneisbasedontheenergyormovementofthedifferentprocessingmethodsofthecomposite;KairnleyTheotherisbasedontheprincipleofprocessconcentratio......
  • [米联客-安路飞龙DR1-FPSOC] FPGA基础篇连载-17 I2C通信协议原理
    软件版本:Anlogic-TD5.9.1-DR1_ES1.1操作系统:WIN1064bit硬件平台:适用安路(Anlogic)FPGA实验平台:米联客-MLK-L1-CZ06-DR1M90G开发板板卡获取平台:https://milianke.tmall.com/登录"米联客"FPGA社区http://www.uisrc.com视频课程、答疑解惑! 1概述    我们知道I......
  • [米联客-安路飞龙DR1-FPSOC] FPGA基础篇连载-18 I2C MASTER控制器驱动设计
    软件版本:Anlogic-TD5.9.1-DR1_ES1.1操作系统:WIN1064bit硬件平台:适用安路(Anlogic)FPGA实验平台:米联客-MLK-L1-CZ06-DR1M90G开发板板卡获取平台:https://milianke.tmall.com/登录"米联客"FPGA社区http://www.uisrc.com视频课程、答疑解惑! 1系统框图I2CMaster控......
  • helm chart 仓库chartmuseum
    安装harbor的helmchartrepository默认新版harbor不会启用chartrepositoryservice,如果需要管理helm,我们需要在安装时添加额外的参数,例如:默认安装是下面这样的$cd/usr/local/harbor$./install.sh启用chartrepositoryservice服务的安装方式要添加一个参数--with-......
  • 臂式血压仪pcba方案设计与开发
    臂式血压仪是运用电子技术与血压间接测量原理进行血压测量的医疗设备。臂式血压仪有臂式、腕式、手表式之分;其电子技术已经历了最原始的第一代(机械式定速排气阀)、第二代(电子伺服阀)、第三代(加压同步测量)及第四代(集成气路)的发展。通常由阻塞袖带、传感器(气压计)、电磁阀、充气泵......
  • C#动态计算字符串中的表达式
    最近遇到一个需要计算字符串中表达式的需求,需要从字符串公式中动态计算结果。类似下面这样1stringexpression="Age*0.2+Height*0.1+log4"; 使用DataTable.Compute函数一开始找的是下面这种方法,但是不能计算对数1usingSystem.Data;23DataTabledt=ne......
  • 纯CSS实现气泡框效果
    目标效果实现<divclass="poptriangle-border">Hello</div>/*气泡框类*/.pop{...}/*气泡尖角伪元素*/.triangle-border:before{content:'';position:absolute;top:10px;/*controlsverticalposition*/bottom:auto;lef......
  • [十万个为什么] [lua] packfield
    localfunctionprint_pack_field(s) localcnt=s:byte(5) fori=1,#sdo ifi==1then io.write("size:") elseifi==5then io.write("\ncnt:") elseifi==7then io.write("\nname_ref:") e......