C# 为什么两个线程不能同时等待一个Mutex 释放
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSy...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Mutex互斥
{
class Program
{
static Mutex gMs; //关联线程关系
//2个信号灯 都是无信号
static AutoResetEvent Event1 = new AutoResetEvent(false);
static AutoResetEvent Event2 = new AutoResetEvent(false);
static void Main(string[] args)
{
Console.WriteLine("开始运行");
gMs = new Mutex(true);
//为后面的线程t1,t2,定义AutoResetEvent对象
AutoResetEvent[] evs = new AutoResetEvent[2];
evs[0] = Event1;
evs[1] = Event2;
Program th = new Program();
Thread t1 = new Thread(new ThreadStart(th.t1Start));
Thread t2 = new Thread(new ThreadStart(th.t2Start));
t1.Start( );
t2.Start( );
Thread.Sleep(2000);
Console.WriteLine("gMs 释放");
gMs.ReleaseMutex();
WaitHandle.WaitAll(evs); //等待所有2个线程结束
Console.WriteLine(" 全部结束");
Console.ReadLine();
}
public void t1Start( )
{
Console.WriteLine("t1开始");
gMs.WaitOne();
Console.WriteLine("t1完成");
Event1.Set( ); //线程结束,将Event1设置为有信号状态
}
public void t2Start( )
{
Console.WriteLine("t2开始");
gMs.WaitOne( );//等待gMs的释放
Console.WriteLine("t2结束");
Event2.Set( );//线程结束,将Event2设置为有信号状态
}
}
}
//gM.WaitOne(); 会报错“ 由于出现被放弃的 mutex,等待过程结束。” 展开
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Mutex互斥
{
class Program
{
static Mutex gMs; //关联线程关系
//2个信号灯 都是无信号
static AutoResetEvent Event1 = new AutoResetEvent(false);
static AutoResetEvent Event2 = new AutoResetEvent(false);
static void Main(string[] args)
{
Console.WriteLine("开始运行");
gMs = new Mutex(true);
//为后面的线程t1,t2,定义AutoResetEvent对象
AutoResetEvent[] evs = new AutoResetEvent[2];
evs[0] = Event1;
evs[1] = Event2;
Program th = new Program();
Thread t1 = new Thread(new ThreadStart(th.t1Start));
Thread t2 = new Thread(new ThreadStart(th.t2Start));
t1.Start( );
t2.Start( );
Thread.Sleep(2000);
Console.WriteLine("gMs 释放");
gMs.ReleaseMutex();
WaitHandle.WaitAll(evs); //等待所有2个线程结束
Console.WriteLine(" 全部结束");
Console.ReadLine();
}
public void t1Start( )
{
Console.WriteLine("t1开始");
gMs.WaitOne();
Console.WriteLine("t1完成");
Event1.Set( ); //线程结束,将Event1设置为有信号状态
}
public void t2Start( )
{
Console.WriteLine("t2开始");
gMs.WaitOne( );//等待gMs的释放
Console.WriteLine("t2结束");
Event2.Set( );//线程结束,将Event2设置为有信号状态
}
}
}
//gM.WaitOne(); 会报错“ 由于出现被放弃的 mutex,等待过程结束。” 展开
2个回答
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询