关于.net中的mutex

来源:互联网 发布:mac双系统win驱动 编辑:程序博客网 时间:2024/05/16 11:18
今天在做项目的过程中,由于在执行schedule的时候,由于SessionFactory 是一个公有的变量!如果每个线程同时进行的话,那么前面执行过的线程的SessionFactory会被后面的一个覆盖,因此看了一下.net中的mutex类!
        private static Mutex mut = new Mutex();
        private const int numIterations = 1;
        private const int numThreads = 3;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            for(int i = 0; i < numThreads; i++)
            {
                Thread myThread = new Thread(new ThreadStart(MyThreadProc));
                myThread.Name = String.Format("Thread{0}", i + 1);
                myThread.Start();
            }
            Console.ReadLine();
        }
        private static void MyThreadProc()
        {
            for(int i = 0; i < numIterations; i++)
            {
                UseResource();
            }
        }
        private static void UseResource()
        {
            // Wait until it is safe to enter.
            mut.WaitOne();

            Console.WriteLine("{0} has entered the protected area",
                Thread.CurrentThread.Name);

            // Place code to access non-reentrant resources here.

            // Simulate some work.
            //Thread.Sleep(500);

            Console.WriteLine("{0} is leaving the protected area/r/n",
                Thread.CurrentThread.Name);
        
            // Release the Mutex.
            mut.ReleaseMutex();
        }
    }