关于进程同步互斥。我创建了两个程序,但是运行后发现,两个程序并不是轮流访问Mutex.不知道是程序1没有释放还是程序2没有请求。求高人指导!谢谢~
程序1:...省using
namespace NCYS1
{
class Program
{
private static bool mutex;
private static Mutex mut1 = new Mutex(false, "MyMutex", out Program.mutex);
static void Main(string[] args)
{
ThreadStart ts1 = new ThreadStart(UseResource1);
Thread myThread = new Thread(ts1);
myThread.Name = String.Format("线程{0}", 1);
myThread.Start();
Console.ReadKey();
} private static void UseResource1()
{
int i=1;
while (true)
{
mut1.WaitOne();
Console.WriteLine("{0}已经进入临界区", Thread.CurrentThread.Name);
Thread.Sleep(1000);
Console.WriteLine("{0}已经离开临界区 {1}\r\n", Thread.CurrentThread.Name,i++);
mut1.ReleaseMutex();
}
}
}
}
程序2:...省using
namespace NEICUNYINSHE
{
class Program
{
private static bool mutex;
private static Mutex mut2 = new Mutex(false, "MyMutex", out Program.mutex);
static void Main(string[] args)
{
ThreadStart ts2 = new ThreadStart(UseResource2);
Thread myThread = new Thread(ts2);
myThread.Name = String.Format("线程{0}", 2);
myThread.Start();
Console.ReadKey();
} private static void UseResource2()
{
int i=1;
while (true)
{
mut2.WaitOne();
Console.WriteLine("{0}已经进入临界区", Thread.CurrentThread.Name);
Thread.Sleep(1000);
Console.WriteLine("{0}已经离开临界区 {1}\r\n", Thread.CurrentThread.Name,i++);
mut2.ReleaseMutex();
}
}
}
}Mutex进程C#
程序1:...省using
namespace NCYS1
{
class Program
{
private static bool mutex;
private static Mutex mut1 = new Mutex(false, "MyMutex", out Program.mutex);
static void Main(string[] args)
{
ThreadStart ts1 = new ThreadStart(UseResource1);
Thread myThread = new Thread(ts1);
myThread.Name = String.Format("线程{0}", 1);
myThread.Start();
Console.ReadKey();
} private static void UseResource1()
{
int i=1;
while (true)
{
mut1.WaitOne();
Console.WriteLine("{0}已经进入临界区", Thread.CurrentThread.Name);
Thread.Sleep(1000);
Console.WriteLine("{0}已经离开临界区 {1}\r\n", Thread.CurrentThread.Name,i++);
mut1.ReleaseMutex();
}
}
}
}
程序2:...省using
namespace NEICUNYINSHE
{
class Program
{
private static bool mutex;
private static Mutex mut2 = new Mutex(false, "MyMutex", out Program.mutex);
static void Main(string[] args)
{
ThreadStart ts2 = new ThreadStart(UseResource2);
Thread myThread = new Thread(ts2);
myThread.Name = String.Format("线程{0}", 2);
myThread.Start();
Console.ReadKey();
} private static void UseResource2()
{
int i=1;
while (true)
{
mut2.WaitOne();
Console.WriteLine("{0}已经进入临界区", Thread.CurrentThread.Name);
Thread.Sleep(1000);
Console.WriteLine("{0}已经离开临界区 {1}\r\n", Thread.CurrentThread.Name,i++);
mut2.ReleaseMutex();
}
}
}
}Mutex进程C#
看运行结果可见,从第6次开始程序2就不再获得Mutex了,不知是程序2不获得,还是程序1没有释放。但是再过几次程序2还是会继续得到Mutex,然后过几次又得不到,这样循环,为什么会这样,知道的朋友说说
但是,没有看到MSDN参考说mutex可以保证“公平性”(先到先服务)。在你的例子中,你想要的应该是“公平性”。