using System;
using System.Threading;
public class philosopher_dining
{
private static Semaphore[] self = new Semaphore[5]; //number of chopsticks per pholosophor
private static Semaphore preventStavation = new Semaphore(0, 4);//allow 4 persons pickup
private static int seed = 12;//time
private enum status
{
thinking, hungry, eating,
}
private static status[] states;
private static void pickup(int i)
{
preventStavation.WaitOne();// wait to eat
states[i] = status.hungry;
Console.WriteLine("philosopher {0} is hungry and wants to eat.", i);
test(i);// look for two resources
if (states[i] != status.eating)
self[i].WaitOne(); //the waiting personn
else preventStavation.Release(); //if there are enough resources
Console.WriteLine("philosopher {0} picked up chopsticks and began to eat.", i);
Random fixRand = new Random(seed);
seed++;
int r = fixRand.Next() % 3000;
Thread.Sleep(r);
Console.Write("After {0} time,", r);
Console.WriteLine("philosopher {0} put down chopsticks and beggin thinking.", i);
putdown(i);
preventStavation.Release();
}
private static void putdown(int i)
{
states[i] = status.thinking;
test((i + 4) % 5);
test((i + 1) % 5);
}
private static void test(int i)// look for two resources and change states
{
if (states[(i + 4) % 5] != status.eating &&
states[(i + 1) % 5] != status.eating &&
states[i] == status.hungry)
{
states[i] = status.eating;
self[i].Release();
}
}
public static void Main()
{
for (int i = 0; i < 5; i++)
self[i] = new Semaphore(0, 1);
preventStavation.Release();
states = new status[5];
for (int i = 0; i < 5; i++)
states[i] = status.thinking;
for (int i = 0; i < 5; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(Dining));
t.Start(i);
}
Thread.Sleep(500);//block semapphore
Console.ReadKey();
}
private static void Dining(object i)
{
Random fixRand = new Random(seed);
seed++;
int r = fixRand.Next() % 1000;
Thread.Sleep(r);
pickup((int)i);
}
}