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; } } } } }
标签:Console,Thread,C#,static,Mutex,Semaphore,new,多线程 From: https://www.cnblogs.com/chen1880/p/18685016