0

我运行下面的代码,期望在我第二次锁定互斥锁时锁定流。运行它两次后,我意识到它可以多次锁定(假设在同一个线程中)而不会停止。我该如何改变这种行为?

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

1 回答 1

3

首先,我不确定您是否真的了解互斥锁,您只能在它们开始被锁定的上下文(即线程)中释放它们,因此将它们用作某种保护点没有什么意义。

在这种情况下使用信号量可能更有意义。但是你仍然应该弄清楚你真正想做的事情:)

使用系统;
使用 System.Collections.Generic;
使用 System.Text;

使用 System.Threading;

命名空间测试
{
    课堂节目
    {
        静态信号量 sem1 = new Semaphore(1, 1);
        静态信号量 sem2 = new Semaphore(1, 1);
        静态无效主要(字符串 [] 参数)
        {           
            sem1.WaitOne(); Console.WriteLine("1W");
            sem2.WaitOne(); Console.WriteLine("2W");
            线程 oThread = new Thread(new ThreadStart(fn2));
            oThread.Start();
            sem1.WaitOne(); Console.WriteLine("1W");
            Console.WriteLine("第二");
            sem1.Release(); Console.WriteLine("1R");
        }
        静态无效 fn2()
        {
            Console.WriteLine("First");
            sem2.Release(); Console.WriteLine("2R");
            sem1.Release(); Console.WriteLine("1R");
        }
    }
}
于 2009-12-13T14:10:14.410 回答