dining philosopher problem
807569Sep 23 2006 — edited Sep 23 2006Write a multi-thread program as a solution for the problem of dining philosophers. The monitor dining controls the distribution of the chopsticks.
This code is written in C; your java code will be different. You have to write a similar code with whatever
Java offers you! (use wait and notifyall)
Monitor dining
{
enum {thinking, hungry, eating} state[5];
void pickup (int i) {
state[i] = hungry;
test(i);
if (state != eating)
self [i].wait();
}
void putdown (int i) {
state [i] = thinking;
test ((i+4) % 5);
test ((i+1) % 5);
}
void test (int i) {
if ((state[(i+4) % 5] != eating) && (state[i] == hungry) &&
(state[(i+1) % 5] !=eating )) {
state[i] = eating;
self [i].signal();
}
}
void init() {
for (int i = 0; i < 5 ; i++)
state[i] = thinking;
}
}
Each philosopher, before starting to eat, must invoke the operation pickup. This may result in the suspension of the philosopher process. After the successful completion of the operation, the philosopher may eat. Following this the philosopher invokes the putdown operation, and may start to think. Thus, philosopher i must invoke the operations pickup and putdown in the following sequence:
Philosopher.pickup( i );
�
eat
�
Philosopher.putdown( i );
In thinking and eating states, you need to use the sleep method to create a random delay for each state.
-- You need to count the number of times that each philosopher gets to eat to see if starvation happens.
Hint: In Java, you cannot notify a specific thread; you just can notify a thread or all threads. Therefore, the above algorithm needs to be modified or rewritten in a different way