C# 多线程同步(Mutex | Semaphore)

Mutex: 用于保护临界区,确保同一时间只有一个线程能够访问共享资源;
Semaphore: 允许同时有多个线程访问共享资源,但会限制并发访问的数量。

 

Mutex运行输出

 

Semaphore运行输出

 

复制代码
namespace SyncThreadDemo
{
    internal class Program
    {
        static string strlock = "Semaphore";// Mutex | Semaphore
        static Mutex mutex = new Mutex();
        static Semaphore semaphore = new Semaphore(2, 2); // 允许同时有两个线程访问

        static void Main(string[] args)
        { 
            Thread[] threads = new Thread[3];
            for (int i = 0; i < 3; i++) { threads[i] = new Thread(new ThreadStart(ThreadMethod)); threads[i].Name = "Thread-" + (i + 1); }
            for (int i = 0; i < 3; i++) { threads[i].Start(); }
            Console.ReadKey();
        }

        static void ThreadMethod()
        {
            Console.WriteLine($"{Thread.CurrentThread.Name} is waiting");

            // 锁住
            switch (strlock)
            {
                case "Mutex": mutex.WaitOne(); break;
                case "Semaphore": semaphore.WaitOne(); break;
            }

            try
            {
                Console.WriteLine($"{Thread.CurrentThread.Name} has acquired");
                Thread.Sleep(100);// 模拟执行动作
            }
            finally
            {
                Console.WriteLine($"{Thread.CurrentThread.Name} is releasing"); 

                // 解锁
                switch (strlock)
                {
                    case "Mutex": mutex.ReleaseMutex(); break;
                    case "Semaphore": semaphore.Release(); break;
                }
            }
        } 
    }
}
复制代码

 

posted @   CHHC  阅读(10)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示