如何使互斥锁不递归 [英] How to make the mutex not be recursive

查看:88
本文介绍了如何使互斥锁不递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行了下面的代码,期望第二次锁定互斥锁时流被锁定.在运行两次之后,我意识到它可以锁定很多次(假设在同一线程中)而不会停止.如何更改此行为?

I ran the code below expecting flow to be locked on the 2nd time I lock a mutex. After running it twice I realize it can lock many times (assuming in the same thread) without stopping. How do I change this behavior?

using System;
using System.Collections.Generic;
using System.Text;

using System.Threading;

namespace Test {
    class Program {
        static volatile Mutex mut1 = new Mutex();
        static volatile Mutex mut2 = new Mutex();
        static void Main(string[] args) {
            mut1.WaitOne(); Console.WriteLine("1W");
            mut2.WaitOne(); Console.WriteLine("2W");
            Thread oThread = new Thread(new ThreadStart(fn2));
            oThread.Start();
            mut1.WaitOne(); Console.WriteLine("1W");
            Console.WriteLine("Second");
            mut1.ReleaseMutex(); Console.WriteLine("1R");
        }
        static void fn2() {
            Console.WriteLine("First");
            mut2.ReleaseMutex(); Console.WriteLine("2R");
            mut1.ReleaseMutex(); Console.WriteLine("1R");
        }
    }
}

推荐答案

首先,我不确定您是否真的了解互斥体,您只能在它们被锁定为开始的上下文(即线程)中释放它们,因此将它们用作某种防护点毫无意义.

For a start I am not sure you really understand mutexes, you can only release them in the context (i.e. thread) in which they were locked to begin with, so using them as some sort of guard points makes little sense.

使用信号量在这种情况下.但是您仍然应该弄清楚自己真正想做的事情:)

It might make more sense to use semaphores in this case. But you still should work out what you are really trying to do :)

using System;
using System.Collections.Generic;
using System.Text;

using System.Threading;

namespace Test
{
    class Program
    {
        static Semaphore sem1 = new Semaphore(1, 1);
        static Semaphore sem2 = new Semaphore(1, 1);
        static void Main(string[] args)
        {           
            sem1.WaitOne(); Console.WriteLine("1W");
            sem2.WaitOne(); Console.WriteLine("2W");
            Thread oThread = new Thread(new ThreadStart(fn2));
            oThread.Start();
            sem1.WaitOne(); Console.WriteLine("1W");
            Console.WriteLine("Second");
            sem1.Release(); Console.WriteLine("1R");
        }
        static void fn2()
        {
            Console.WriteLine("First");
            sem2.Release(); Console.WriteLine("2R");
            sem1.Release(); Console.WriteLine("1R");
        }
    }
}

这篇关于如何使互斥锁不递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆