难道分别在不同线程中的mutex.waitany(gms)与mutex.waitall(gms)不能够等待同一个mutex对象吗???
using System;
using System.Threading;
/// <summary>
/// 问题是: Mutex.WaitAll(gMs)与线程3中的 Mutex.WaitAny(gMs) 在等待同一个Mutex对象时,
/// 产生“由于出现被放弃的 mutex,等待过程结束”异常;
/// </summary>
public class MutexSample
{
//------定义两个互斥对象与自动重置事件对象----------
static Mutex gM1; //线程1等待的对象
static Mutex gM2;//线程3等待的对象
static AutoResetEvent Event1 = new AutoResetEvent(false);//线程1执行完成
static AutoResetEvent Event3 = new AutoResetEvent(false);//线程2执行完成
public static void Main(String[] args)
{
Console.WriteLine("MutexSample.cs ...");
gM1 = new Mutex(true);
gM2 = new Mutex(true);
Console.WriteLine(" - Main Owns gM1 and gM2");
AutoResetEvent[] evs = new AutoResetEvent[2];
evs[0] = Event1;
evs[1] = Event3;
MutexSample tm = new MutexSample();
Thread t1 = new Thread(new ThreadStart(tm.t1Start));
Thread t3 = new Thread(new ThreadStart(tm.t3Start));
t1.Start();
t3.Start();
Thread.Sleep(2000);
Console.WriteLine(" - Main releases gM1");
gM1.ReleaseMutex();
Thread.Sleep(2000);
Console.WriteLine(" - Main releases gM2");
gM2.ReleaseMutex();
WaitHandle.WaitAll(evs);
Console.WriteLine("... MutexSample.cs");
}
public void t1Start()
{
Console.WriteLine("t1Start started, Mutex.WaitAll(Mutex[])");
Mutex[] gMs = new Mutex[1];
gMs[0] = gM2;
Mutex.WaitAll(gMs);
Thread.Sleep(2000);
Console.WriteLine("t1Start finished, Mutex.WaitAll(Mutex[])");
Event1.Set();
}
public void t3Start()
{
Console.WriteLine("t3Start started, Mutex.WaitAny(Mutex[])");
Mutex[] gMs = new Mutex[1];
gMs[0] = gM2;
Mutex.WaitAny(gMs);
Event3.Set();
}
}
补充:.NET技术 , C#