You are on page 1of 2

TAREA 2 PROGRAMA “CENA DE LOS FILOSOFOS”.

CÓDIGO:
using System;
using System.Threading;

namespace cenaComensales
{
class Program
{
static int i = 0;
public static int N = 5;
static int LEFT = (i + N - 1) % N;
static int RIGHT = (i + 1) % N;
const int THINKING = 0;
const int HUNGRY = 1;
const int EATING = 2;
static int[] state = new int[6];
static Semaphore mutex = new Semaphore(1,1);
static Semaphore[] s = new Semaphore[6];
static Thread[] threads = new Thread[6];

static void Main(string[] args)


{

for (i = 1; i <=5; i++)


{
s[i] = new Semaphore(0, 1);
threads[i] = new Thread(philosopher);
threads[i].Name = "" + i;
threads[i].Start();
state[i] = THINKING;
}
Console.Read();

static void philosopher()


{
while (true)
{
thinking(Int32.Parse(Thread.CurrentThread.Name));
take_forks(Int32.Parse(Thread.CurrentThread.Name));
eat(Int32.Parse(Thread.CurrentThread.Name));
put_fork(Int32.Parse(Thread.CurrentThread.Name));
Thread.Sleep(3000);

}
}

static void take_forks(int i)


{
mutex.WaitOne();
state[i] = HUNGRY;
test(i);
mutex.Release();
s[i].WaitOne();
}
static void put_fork(int i)
{
thinking(i);
mutex.WaitOne();
state[i] = THINKING;
test(LEFT);
test(RIGHT);
mutex.Release();
}

static void thinking(int i)


{
Console.WriteLine("Filosofo {0} pensando ", i);
}

static void hungry(int i)


{
Console.WriteLine(" Filosofo {0} hambriento
", i);
}

static void eat(int i)


{
Console.WriteLine("
Filosofo {0} comiendo ", i);
}

static void test(int i)


{
if (state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING)
{
state[i] = EATING;
s[i].Release();
}

}
}

You might also like