Given the dining philosophers problem with 3 philosophers gi
Given the dining philosophers problem with 3 philosophers give pseudocode to prevent synchronization problems and allow all the philosophers to eat (eventually). Explain if your solution is fair or not and whether it avoids indefinite postponement.
Solution
monitor diningPhilosophers { int[] state = new int[5]; boolean[] leftHungry = new boolean[5]; boolean[] rightHungry = new boolean[5]; static final int THINKING = 0; static final int HUNGRY = 1; static final int EATING = 2; condition[] self = new condition[5]; public diningPhilosophers { for (int i=0;i<5;i++) { state[i] = THINKING; leftHungry[i] = false; rightHungry[i] = false; } } public entry pickUp(int i) { state[i] = HUNGRY; test(i); if (state[i] != EATING) self[i].wait; rightHungry(left(i)) = false; leftHungry(right(i)) = false; } public entry putDown(int i) { state[i] = THINKING; test(left(i)); if (state[left(i)] == HUNGRY) leftHungry[i] = true; test(right(i)); if (state[right(i)] == HUNGRY) rightHungry[i] = true; } private test(int i) { if (state[right(i] != EATING) && (state[i] == HUNGRY) && (state[left(i)] != EATING) && !leftHungry(i) && !rightHungry(i) ) { state[i] = EATING; self[i].signal; } } private int left(int i) { return (i+1)%5; } private int right(int i) { return (i+4)%5; } }