【发布时间】:2023-03-14 02:29:01
【问题描述】:
是否有可能(在 .net 中)让线程等待信号量“完全发出信号”?具体来说,这就是我正在寻找的:
在主线程中创建信号量。 使用 .WaitOne() 将许多其他线程排队。 释放所有信号量的句柄。 等待其所有句柄为“空”。 在主线程中恢复操作。
为清楚起见,这里是一些经过精心设计的代码:
using System;
using System.Threading;
namespace ConcurrencySample01
{
class Program
{
private static Semaphore _MaitreD = new Semaphore(0, 4);
private static Random _Rnd = new Random();
static void Main(string[] args)
{
Console.WriteLine("The restaurant is closed. No one can eat.");
Thread.Sleep(1000);
for (int i = 1; i <= 6; i++)
{
Thread t = new Thread(Diner);
t.Start(i);
}
Console.WriteLine("The restaurant is opening.");
Console.WriteLine("Empty seat count: {0}", 4 - _MaitreD.Release(4));
// HERE IS WHERE I WANT TO WAIT.
Console.WriteLine("The table is empty.");
Console.ReadLine();
}
private static void Diner(object num)
{
Console.WriteLine("Diner {0} enters the restaurant and requests a seat.", num);
_MaitreD.WaitOne();
Console.WriteLine("Diner {0} sits down and begins to eat.", num);
Thread.Sleep(1000 + _Rnd.Next(1000));
Console.WriteLine("Diner {0} finishes and gets up.", num);
Console.WriteLine("Empty seat count: {0}", _MaitreD.Release() + 1);
}
}
}
【问题讨论】:
标签: .net multithreading concurrency semaphore