Chandy Misra Solution
Chandy Misra Solution to the dining philosophers problem
by scotp71
HTML
<h2>
Dining Philosophers Problem
</h2>
<input type='button' value='Start Dinner' onclick="startDinner()"/>
<div id="output">
</div>
CSS
h2 {
text-align: center;
}
p {
text-align: center;
color: red;
}
input {
text-align: center;
}
#randomButton {
width: 300px;
padding: 10px;
text-align: center;
color: blue;
}
JavaScript
//COP 4610 Spring 2019
//Programming Assignment 3 - Dining Philosophers Problem - Chandy Misra Solution
//Written By Scot Pfeffer
var n = 5;
var canEat = false;
var forks = [];
var philosophers = [];
function Fork(y){
this.id = y;
this.dirty = true;
this.owner = null;
}
function phil(x){
this.id = x;
this.hasEaten = false;
}
function startDinner() {
startEating();
print("Dinner is finished.");
}
function print(t){
document.getElementById("output").innerHTML += t + " <br/> ";
}
function addForks(){
for (i=1; i<n+1; i++){
var fork = new Fork(i);
forks.push(fork);
}
}
function addPhilosophers(){
for (i=1; i<n+1; i++){
var philosopher = new phil(i);
philosophers.push(philosopher);
}
}
function startEating(){
addForks();
addPhilosophers();
assignForks();
while (haveAllPhilsEaten()==false){
digIn();
for (i=0; i<n; i++){
if (philosophers[i].hasEaten==true){
var philID = i+1;
for (j=0; j<n; j++){
if(forks[j].owner==philID){
forks[j].dirty=true;
}
}
}
}
print("End of Round " + "<br/>")
}
}
function assignForks(){
for (i=0; i<n; i++){
forks[i].owner = philosophers[i].id;
}
}
function digIn(){
for (i=0; i<n; i++){
if (philosophers[i].hasEaten==true){
print("Philosopher " + (i+1) + " is now thinking");
}
if (philosophers[i].hasEaten==false){
var minFork = Math.min((i), ((i+1)%5));
var maxFork = Math.max((i), ((i+1)%5));
var hasMin = hasFork(i, minFork);
var hasMax = hasFork(i, maxFork);
if (hasMin!=true){
if(requestFork(i, minFork)==true){
hasMin=true;
}
}
if (hasMin==true && hasMax!=true){
if (requestFork(i, maxFork)==true){
hasMax=true;
}
}
if (hasMin==true && hasMax==true){
philCanEat(i);
}
else
print("Philosopher " + (i+1) + " is now thinking");
}
}
}
function hasFork(i, j){
var...