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()需成對配合使用。