Mutex
一、简介
Mutex的突出特点是可以跨应用程序域边界对资源进行独占访问,即可以用于同步不同进程中的线程,这种功能当然这是以牺牲更多的系统资源为代价的。
主要常用的两个方法:
public virtual bool WaitOne() 阻止当前线程,直到当前 System.Threading.WaitHandle 收到信号获取互斥锁。
public void ReleaseMutex() 释放 System.Threading.Mutex 一次。
二、代码
案例一:
class Program { private static Mutex mutex = new Mutex(); static void Main(string[] args) { Thread[] thread = new Thread[3]; for (int i = 0; i < 3; i++) { thread[i] = new Thread(ThreadMethod1);//方法引用 thread[i].Name = "Thread-" + (i+1).ToString(); } for (int i = 0; i < 3; i++) { thread[i].Start(); } Console.ReadKey(); } public static void ThreadMethod1(object val) { mutex.WaitOne(); //获取锁 for (int i = 1; i <=5; i++) { Console.WriteLine("{0}循環了{1}次", Thread.CurrentThread.Name, i); } mutex.ReleaseMutex(); //释放锁 } }
运行结果:
案例二:
class Program { private static Mutex mutex = new Mutex(); private static int sum = 0; static void Main(string[] args) { Task<int> task = new Task<int>(ThreadFunction); task.Start(); Console.WriteLine($"{DateTime.Now} task started!"); Thread.Sleep(2000);//Main主線程 Console.WriteLine($"{DateTime.Now} Get siginal in Main!"); mutex.WaitOne(); Console.WriteLine($"{DateTime.Now} Get siginal in main!"); Console.WriteLine($"{DateTime.Now} Result is {task.Result}"); Console.ReadKey(); } private static int ThreadFunction() { Console.WriteLine($"{DateTime.Now} Get siginal in ThreadFunction!"); mutex.WaitOne(); //获取锁 for (int i = 0; i <= 10; i++) { sum += i; Thread.Sleep(1000); } Console.WriteLine($"{DateTime.Now} Release mutex in ThreadFunction!"); mutex.ReleaseMutex(); //释放锁 return sum; } }
运行结果:
三、总结
为避免发送多线程发生死锁,Mutex的WaitOne()和ReleaseMutex()需成对配合使用。