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;
                }
            }
        } 
    }
}

复制代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值