我正在使用 C# 处理信号量。以下是我对C# 中的Release
和方法的理解。WaitOne
该WaitOne
方法在线程进入槽时减少信号量计数,当它离开槽时,信号量增加。
该Release
方法返回以前的信号量计数对吗?我的理解与以下代码相矛盾:
static Thread[] threads = new Thread[5];
static Semaphore sem = new Semaphore(3,5);
static void SemaphoreTest()
{
Console.WriteLine("{0} is waiting in line...", Thread.CurrentThread.Name);
Console.WriteLine("Semaphore count : "+sem.WaitOne());
Console.WriteLine("{0} enters the semaphore test", Thread.CurrentThread.Name);
Thread.Sleep(300);
Console.WriteLine("{0} is leaving the semaphore test and the semaphore count is {1}", Thread.CurrentThread.Name, sem.Release());
}
static void Main(string[] args)![enter image description here][2]
{
for (int i = 0; i < 5; i++)
{
threads[i] = new Thread(SemaphoreTest);
threads[i].Name = "thread_" + i;
threads[i].Start();
}
Console.Read();
Thread_2离开,因此信号量计数必须增加。但这并没有发生,因为当thread_0即将离开时,先前的信号量计数为 0。根据我的理解,它必须是一个。我对吗?谁能解释一下?