C#互斥锁Mutex的应用

以下是通过C#编写的控制台程序,具体是在线程间调用互斥锁。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//use the mutex and thread
using System.Threading;


namespace UseMytex
{
    class Program
    {
        // Create a new Mutex. The creating thread does not own the mutex. 

        private static Mutex mut = new Mutex(false, "mutes1");     //false : Mutex未被占有
        private const int numIterations = 1;     //循环调用函数的次数
        private const int numThreads = 3;       //3个线程


        static void Main(string[] args)
        {
            // Create the threads that will use the protected resource. 

            for (int i = 0; i < numThreads; i++)
            {
                Thread newThread = new Thread(new ThreadStart(ThreadProc));
                newThread.Name = String.Format("Thread{0}", i + 1);
                newThread.Start();
            }

            // The main thread exits, but the application continues to 
            // run until all foreground threads have exited.
            Console.ReadLine();
        }


        private static void ThreadProc()
        {
            for (int i = 0; i < numIterations; i++)
            { 
                UseResource();
            }
        }

        // This method represents a resource that must be synchronized 
        // so that only one thread at a time can enter. 

        private static void UseResource()
        {
            // Wait until it is safe to enter, and do not enter if the request times out.
            Console.WriteLine("{0} is requesting the mutex", Thread.CurrentThread.Name);  //得到当前正在请求的线程名称

            if (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(5000);

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


                // Release the Mutex.
                mut.ReleaseMutex();     //释放当前得到的互斥量
                Console.WriteLine("{0} has released the mutex",
                                  Thread.CurrentThread.Name);
            }
            else
            {
                Console.WriteLine("{0} will not acquire the mutex",
                                  Thread.CurrentThread.Name);
            }
        }
    }

}

在关闭程序时,除了关闭线程  Thread.Abort(),

还需要将互斥锁进行释放   mutex.ReleaseMutex();   


结果如下图所示:



猜你喜欢

转载自blog.csdn.net/qq_31094099/article/details/80308367