How do i make the mutex not be recusive?

一世执手 提交于 2019-12-08 11:06:30

问题


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");
        }
    }
}

回答1:


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");
        }
    }
}


来源:https://stackoverflow.com/questions/1896581/how-do-i-make-the-mutex-not-be-recusive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!