日期:2014-05-17  浏览次数:20891 次

进程间使用Mutex问题求解
关于进程同步互斥。我创建了两个程序,但是运行后发现,两个程序并不是轮流访问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)
        {