惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Vulnerabilities – Threatpost
AI
AI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
L
LINUX DO - 热门话题
G
GRAHAM CLULEY
Cisco Talos Blog
Cisco Talos Blog
T
Tenable Blog
L
Lohrmann on Cybersecurity
Know Your Adversary
Know Your Adversary
A
Arctic Wolf
T
Threatpost
AWS News Blog
AWS News Blog
S
Securelist
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
J
Java Code Geeks
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
Cisco Blogs
F
Full Disclosure
Jina AI
Jina AI
Engineering at Meta
Engineering at Meta
I
InfoQ
C
CXSECURITY Database RSS Feed - CXSecurity.com
I
Intezer
C
CERT Recently Published Vulnerability Notes
Last Week in AI
Last Week in AI
P
Privacy International News Feed
Scott Helme
Scott Helme
WordPress大学
WordPress大学
Simon Willison's Weblog
Simon Willison's Weblog
D
Docker
T
Threat Research - Cisco Blogs
P
Proofpoint News Feed
C
Cyber Attacks, Cyber Crime and Cyber Security
Y
Y Combinator Blog
T
Tor Project blog
V
Visual Studio Blog
Spread Privacy
Spread Privacy
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
Google Online Security Blog
Google Online Security Blog
C
Check Point Blog
爱范儿
爱范儿
N
News and Events Feed by Topic
博客园 - 【当耐特】
TaoSecurity Blog
TaoSecurity Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main

博客园 - 码 头

实测有效:Win11右键默认显示更多设置教程 HTML转义字符大全 .Net Core后台任务启停(BackgroundService) 常见的JavaScript的循环处理数据方法 Linux下.NET Core进程守护设置,解决SSH关闭后.NET Core服务无法访问的问题 记录 IIS 部署vue 项目步骤 AspNetCoreApi 跨域处理(CORS ) .NET CORE 使用Session报错:Session has not been configured for this application or request 小豆苗疫苗辅助搜索 日期函数(sql) 图片javascript缩小 c# DESEncrypt 加密、解密算法 汉字编码问题转换 二分法算法 MVC拦截器记录操作用户日志 最全的Resharper快捷键汇总 如何将数据库中的表导入到PowerDesigner中 修复IE9.0下PlaceHolder 属性问题js脚本 sql脚本查询日期时间段日期
netcore 并发锁 多线程中使用SemaphoreSlim
码 头 · 2024-04-16 · via 博客园 - 码 头

SemaphoreSlim是一个用于同步和限制并发访问的类,和它类似的还有Semaphore,只是SemaphoreSlim更加的轻量、高效、好用。今天说说它,以及如何使用,在什么时候去使用,使用它将会带来什么优势。

代码的业务是:

在多线程下进行数据的统计工作,简单点的说就是累加数据。

1.首先我们建立一个程序

代码如下

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConsoleApp2
{
    class Program
    {
        static int a = 0;
        static async Task Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Task t1 = Task.Run(() =>
            {
                A();
            });
 
            Task t2 = Task.Run(() =>
            {
                B();
            });
            await Task.WhenAll(t1, t2);
            stopwatch.Stop();
            Console.WriteLine("总时间:" + stopwatch.ElapsedMilliseconds);
            Console.WriteLine("总数:" + a);
            Console.ReadLine();
        }
        private static void A()
        {
            for (int i = 0; i < 100_0000; i++)
            {
                a++;
            }
        }
 
        private static void B()
        {
            for (int i = 0; i < 100_0000; i++)
            {
                a++;
            }
        }
 
    }
}

  2.运行结果

此时需要多运行几次,会发现,偶尔出现运行的结果不一样,这就是今天的问题

3.分析结果

从结果看,明显错误了,正确答案是:200 0000,但是第二次的结果是131 6465。我们的业务就是开启2个线程,一个A方法,一个B方法,分别对a的数据进行累加计算。那么为什么造成这样的结果呢?

造成这样的原因就是多线程的问题。

解决方法一:

1.使用lock

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConsoleApp2
{
    class Program
    {
        static int a = 0;
        static object o = new object();
        static async Task Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Task t1 = Task.Run(() =>
            {
                A();
            });
 
            Task t2 = Task.Run(() =>
            {
                B();
            });
            await Task.WhenAll(t1, t2);
            stopwatch.Stop();
            Console.WriteLine("总时间:" + stopwatch.ElapsedMilliseconds);
            Console.WriteLine("总数:" + a);
            Console.ReadLine();
        }
        private static void A()
        {
            for (int i = 0; i < 100_0000; i++)
            {
                lock (o)
                {
                    a++;
                }
            }
        }
 
        private static void B()
        {
            for (int i = 0; i < 100_0000; i++)
            {
                lock (o)
                {
                    a++;
                }
            }
        }
 
    }
}

2. lock的结果

  

当我们增加lock后,不管运行几次,结果都是正确的。 

解决方法二:

1.使用SemaphoreSlim

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConsoleApp2
{
    class Program
    {
        static int a = 0;
        static object o = new object();
        static SemaphoreSlim semaphore = new SemaphoreSlim(1);  //控制访问线程的数量
        static async Task Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Task t1 = Task.Run(() =>
            {
                A();
            });
 
            Task t2 = Task.Run(() =>
            {
                B();
            });
            await Task.WhenAll(t1, t2);
            stopwatch.Stop();
            Console.WriteLine("总时间:" + stopwatch.ElapsedMilliseconds);
            Console.WriteLine("总数:" + a);
            Console.ReadLine();
        }
        private static void A()
        {
            for (int i = 0; i < 100_0000; i++)
            {
                semaphore.Wait();
                //lock (o)
                //{
                a++;
                //}
                semaphore.Release();
            }
        }
 
        private static void B()
        {
            for (int i = 0; i < 100_0000; i++)
            {
                semaphore.Wait();
                //lock (o)
                //{
                a++;
                //}
                semaphore.Release();
            }
        }
 
    }
}

2.SemaphoreSlim的效果

当我们增加SemaphoreSlim后,不管运行几次,结果都是正确的。

4.我们对比方法一和方法二发现,他们的结果都是一样的,但是lock似乎比SemaphoreSlim更加的高效,是的,lock解决此业务的确比SemaphoreSlim高效。但是lock能干的事,SemaphoreSlim肯定能干,SemaphoreSlim能干的事,lock不一定能干。

5.SemaphoreSlim的使用

SemaphoreSlim使用的范围非常的广,可以限制访问资源的线程数,例如限制一个资源最多5个线程可以同时访问

using System.Threading;
 
class Program
{
    static SemaphoreSlim semaphore = new SemaphoreSlim(5); // 允许最多5个线程同时访问资源
 
    static void Main()
    {
        for (int i = 0; i < 10; i++)
        {
            Task.Run(DoWork);
        }
        Console.ReadLine();
    }
 
    static async Task DoWork()
    {
        await semaphore.WaitAsync(); // 等待许可
        try
        {
            Console.WriteLine($"线程 {Thread.CurrentThread.ManagedThreadId} 开始工作");
            await Task.Delay(1000); // 模拟耗时操作
            Console.WriteLine($"线程 {Thread.CurrentThread.ManagedThreadId} 结束工作");
        }
        finally
        {
            semaphore.Release(); // 释放许可
        }
    }
}

此时DoWork()这个方法,最多同时只有5个线程访问,当改成1个,就是按照顺序进行了,和lock的使用是一样的

6.总结

如果需要确保同一时间只有一个线程访问某资源(此案例指的就是变量a),那么可以使用Lock,也可以使用SemaphoreSlim;如果需要控制同时访问资源的线程数量,并且需要更复杂的信号量操作,那么可以使用SemaphoreSlim。总之,使用Lock还是SemaphoreSlim,都是根据具体业务而定。

拓展:

当我们在第1步,只需要增加一句话,不增加lock和SemaphoreSlim,依然可以使得计算的结果准确,那就是增加

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConsoleApp2
{
    class Program
    {
        static int a = 0;
        static async Task Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Task t1 = Task.Run(() =>
            {
                A();
            });
 
            Task t2 = Task.Run(() =>
            {
                B();
            });
            await Task.WhenAll(t1, t2);
            stopwatch.Stop();
            Console.WriteLine("总时间:" + stopwatch.ElapsedMilliseconds);
            Console.WriteLine("总数:" + a);
            Console.ReadLine();
        }
        private static void A()
        {
            for (int i = 0; i < 10_0000; i++)
            {
                a++;
                Console.WriteLine(a);
            }
        }
 
        private static void B()
        {
            for (int i = 0; i < 10_0000; i++)
            {
                a++;
                Console.WriteLine(a);
            }
        }
 
    }
}

效果