多线程互斥——Mutex的使用

MSDN的解释为如下

命名空间: System.Threading

当两个或多个线程需要同时访问共享的资源时,系统将需要使用同步机制来确保一次只有一个线程使用的资源。 Mutex 是一个同步基元,授予于只有一个线程对共享资源的独占访问权限。 如果一个线程获取互斥体,第二个想要获取该互斥体挂起线程,直到第一个线程释放此斥锁。

		static void Main(string[] args)
        {
            bool Flag = true;//布尔变量传入,未发现此值对结果存在任何影响
            Mutex mu = new Mutex(true, "Mutex", out Flag);//初始化函数
            //Initializes a new instance of the Mutex class with a Boolean value that indicates whether 
            //the calling thread should have initial ownership of the mutex, a string that is the name 
            //of the mutex, and a Boolean value that, when the method returns, indicates whether the 
            //calling thread was granted initial ownership of the mutex.
            //mutex仅允许存在一个实例运行 对flag进行判断
            if (Flag)
            {
                Console.WriteLine("FIrst");
            }
            else
            {
                Console.WriteLine("has another one");
            }
            Console.Read();
        }

上面的程序只允许运行一次 再次运行会显示已经存在实例
下面的代码则是使用等待释放互斥变量

 static void Main(string[] args)
        {
            bool flag = false;
            using (var m = new Mutex(false, "t1",out flag))
            {
                //调用WaitOne方法,延迟15秒,如果15秒已存在的实例内释放了,则会进入此方法
                if (!m.WaitOne(TimeSpan.FromSeconds(15), false))
                {
                    Console.WriteLine("exit has another one");
                    Console.Read();
                }
                else
                {
                    Console.WriteLine("first");
                    Console.Read();
                    m.ReleaseMutex();//释放一次的方法
                }
            }
        }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值