Sunday, April 13, 2014

Dining Philosopher Solution

From now i'll be posting solutions to some of the programming assignments in my blog :-)

Implementation of Dining Philosopher problem's solution in java :

import java.util.*;
public class DiningPhilosopher
{
public static void main(String[] args)
{
Mutex mut = new Mutex(1);
Chopstick ch[] = new Chopstick[5];
for(int i=0;i<5;i++)
{
ch[i] = new Chopstick();
ch[i].cno = i;
ch[i].in_use = false;
}
// Creating The Philosophers
Philosopher ph[] = new Philosopher[5];

for(int i=0;i<5;i++)
{
ph[i] = new Philosopher(i,ch[i],ch[(i+1)%5],mut);
new Thread(ph[i]).start();
}
}
}
class Philosopher implements Runnable // The "processes" among which the resources are shared
{
Philosopher(int pno, Chopstick left, Chopstick right, Mutex mut)
{
this.pno = pno;
this.left = left;
this.right = right;
this.mut = mut;
}
Mutex mut;
Chopstick left;
Chopstick right;
int state=2; // THINKING by default 1: HUNGRY 2:THINKING 3:EATING
int sem=1;
int pno;
void think()
{
System.out.println("Philosopher "+this.pno+" is Thinking");
}
void takeChopsticks()
{
// turn mutex down ; cannot enter cs if mutex already down ; gets blocked :-P
//down(mutex); // Enter Critical section
mut.downMutex(); // Entering CS
this.state=1;  // State is Hungry
System.out.println("Philosopher "+this.pno+" is HUNGRY");
this.test();   // Trying to acquire two Chopsticks
mut.upMutex();     // Exit Critical Section
semDown(); // Block Philosopher if he did'nt get Chopsticks
}
void eat()
{
System.out.println("Philosopher "+this.pno+" is Eating");
}
void putChopsticks()
{
mut.downMutex(); // Enter Critical section
this.state=2;  // State is thinking
left.in_use = false; // Pick up left chopstick
right.in_use = false; // pick up right chopstick
mut.upMutex(); //up(mutex);   // Exit Critical Section
}
void test()
{
if(left.in_use==false && right.in_use==false && this.state==1) // If Both left and right chopsticks are free //and i am hungry
{
this.state=3; // 3: means Eating
left.in_use = true;
right.in_use = true;
semUp();
}
}
public void run()
{
try{
this.think();
// Thread.sleep(1000);
this.takeChopsticks();
// Thread.sleep(1000);
this.eat();
// Thread.sleep(1000);
this.putChopsticks();
}
catch(Exception e)
{
e.printStackTrace();
}
}
void semUp()
{
this.sem = 1;
}
void semDown()
{
while(this.sem == 0); // blocking condition
this.sem=0;
}
}
class Chopstick // The resources needed to be shared
{
int cno;
boolean in_use; // true for in_use & false for free
void setuse(boolean in_use)
{
this.in_use = in_use;
}
}
class Mutex
{
int mutex;
Mutex(int mutex)
{
this.mutex = mutex;
}
void upMutex()
{
this.mutex = 1;
}
void downMutex()
{
while(this.mutex==0);
this.mutex = 0;

}
}

No comments:

Post a Comment