7
I found this code online while studying and I couldn’t understand two things:
What the traffic light "seatbelt" does?
Why isn’t the barber checking the waiting room after finishing a cut? (It goes directly to the state "Resting")
Thank you very much!
static void Main(string[] args)
{
Random Rand = new Random();
const int MaxCustomers = 3;
const int NumChairs = 3;
Semaphore waitingRoom = new Semaphore(NumChairs, NumChairs);
Semaphore barberChair = new Semaphore(1, 1);
Semaphore barberSleepChair = new Semaphore(0, 1);
Semaphore seatBelt = new Semaphore(0, 1);
bool AllDone = false;
void Barber()
{
while (!AllDone)
{
Console.WriteLine("Barbeiro dormindo.");
barberSleepChair.WaitOne();
if (waitingRoom.ToString() == "3")
{
Console.WriteLine("Barbeiro tem que cortar.");
Thread.Sleep(Rand.Next(1, 3) * 1000);
Console.WriteLine("Barbeiro corta o cabelo.");
seatBelt.Release();
Console.WriteLine("Barbeiro checa a sala de espera");
}
else
{
Console.WriteLine("Barbeiro dormindo.");
}
}
return;
}
void Customer(Object number)
{
int Number = (int)number;
Console.WriteLine("O cliente {0} vai ao salão.", Number);
Thread.Sleep(Rand.Next(1, 5) * 1000);
Console.WriteLine("Cliente {0} está no salão.", Number);
waitingRoom.WaitOne();
Console.WriteLine("Cliente {0} entra na sala de espera.", Number);
barberChair.WaitOne();
waitingRoom.Release();
Console.WriteLine("O cliente acorda o barbeiro", Number);
barberSleepChair.Release();
seatBelt.WaitOne();
barberChair.Release();
Console.WriteLine("Cliente {0} sai do salão.", Number);
}
Thread BarberThread = new Thread(Barber);
BarberThread.Start();
Thread[] Customers = new Thread[MaxCustomers];
for (int i = 0; i < MaxCustomers; i++)
{
Customers[i] = new Thread(new ParameterizedThreadStart(Customer));
Customers[i].Start(i);
}
for (int i = 0; i < MaxCustomers; i++)
{
Customers[i].Join();
}
AllDone = true;
barberSleepChair.Release();
BarberThread.Join();
Console.WriteLine("Fim do trabalho!");
Console.ReadKey();
}
what is Semaphore ? ( what its cosntrusion parameters mean) ?
– le314u
https://docs.microsoft.com/pt-br/dotnet/api/system.threading.semaphore?view=netcore-3.1
– Vitor Ceolin