关于Multex的应用说明
关于Multex的应用说明
Mutex是一个互斥的同步对象,同一时间仅有一个线程可以获得他。
他适合于一个共享资源每次都只能被一个线程访问的情况。
看例子:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace MyTTCon { class shareRes { public static int count = 0; public static Mutex mutex = new Mutex(true); } class IncThread { int number; public Thread thrd; public IncThread(string name, int n) { thrd = new Thread(this.run); number = n; thrd.Name = name; thrd.Start(); } void run() { Console.WriteLine(thrd.Name + "正在等待 the mutex"); //申请 shareRes.mutex.WaitOne(); Console.WriteLine(thrd.Name + "申请到 the mutex"); do { Thread.Sleep(1000); shareRes.count++; Console.WriteLine("In " + thrd.Name + "ShareRes.count is " + shareRes.count); number--; } while (number > 0); Console.WriteLine(thrd.Name + "释放 the nmutex"); // 释放 shareRes.mutex.ReleaseMutex(); } } class DecThread { int number; public Thread thrd; public DecThread(string name, int n) { thrd = new Thread(this.run); number = n; thrd.Name = name; thrd.Start(); } void run() { Console.WriteLine(thrd.Name + "正在等待 the mutex"); //申请 shareRes.mutex.WaitOne(); Console.WriteLine(thrd.Name + "申请到 the mutex"); do { Thread.Sleep(1000); shareRes.count--; Console.WriteLine("In " + thrd.Name + "ShareRes.count is " + shareRes.count); number--; } while (number > 0); Console.WriteLine(thrd.Name + "释放 the nmutex"); // 释放 shareRes.mutex.ReleaseMutex(); } } class Program { static void Main(string[] args) { IncThread mthrd1 = new IncThread("IncThread thread ", 5); DecThread mthrd2 = new DecThread("DecThread thread ", 5); mthrd1.thrd.Join(); mthrd2.thrd.Join(); Console.ReadKey(); } } }
以上代码是摘抄自:http://www.cnblogs.com/tianzhiliang/archive/2010/09/01/1814822.html
下面说明如下:
1) IncThread对象启动一个线程,互斥体它先获得,所以执行后面的操作。直到释放。
DecThread对象后启动一个线程,等上面的线程释放互斥体后,他又可以得到了,这样就可以执行后面的代码了,结果如下:
2) 如果把主程序中的IncThread与DecThread颠倒,先执行DecThread,结果就会不一样,DecThread就会先得到互斥体,结果如下:
3) 如果互斥体的构造函数参数为True,表示的就是第一个获得他的线程拥有它,如果这个线程释放了它后,如果这个线程又结束了,那么其他线程如果再次获得他会报错:
如果这个线程没有结束,那么其他线程也一直获取不到这个互斥体,陷入死循环。
https://files.cnblogs.com/files/monkeyZhong/TestMutex.zip