Waiting for a fully released semaphore?
Is it possible (in .net) to have a thread wait for a semaphore to be "fully signaled?" Specifically, here's what I'm looking for:
Create a Semaphore in a master thread. Queue up a number of other threads using .WaitOne(). Release all of the semaphore's handles. Wait for all of its handles to be "empty." Resume operation in the master thread.
For clarity's sake, here is some ginned-up code:
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);
}
开发者_如何学JAVA 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);
}
}
}
Two synchronization objects are required here. One you already got, a Semaphore models the tables. You need another one to model the door. An event.
精彩评论