ALL > Computer and Education > courses > university courses > undergraduate courses > Operating System > ZSTU-(2020-2021)-1 > student homework > 2018329621176_曹欣然 >
2018329621176_曹欣然_hw07 Version 0
👤 Author: by 439731491qqcom 2021-01-07 10:55:27

#Describe your own example which may encounter deadlocks;


For the Dining-Philosophers Problem, there are five bowls and five chopsticks on the round table. A philosopher usually thinks about it. When he is hungry, he tries to use the chopsticks closest to him on the left and right. He can eat only when he has two chopsticks. After eating, put down the chopsticks and continue thinking. If five philosophers are hungry at the same time and each pick up the chopsticks on the left, which makes the five chopstick semaphores all 0, when they try to pick up the chopsticks on the right, they will all wait indefinitely because they have no chopsticks. That may cause deadlock.



a. show that the four necessary conditions for deadlock indeed holds in this example.


a). Mutal exclusion: when one of them want to eat and pick up both sides of chopsticks, the people next to him will not use the chopsticks at the same time causing the mutual exclusion;


b). Hold and wait: when one of them want to eat and pick up both sides of chopsticks, if the people next to him want to use chopsticks, he will hold his state and wait for the one finishing his eating;


c). No preemption: The waiting people must wait for others next to them finishing eating, so that they can use the chopsticks;


d). Circular wait: The five people sitting around table, everyone is waiting for someone next to him finish eating;



b. state a simple way for avoiding deadlocks in this case.


At most, only four philosophers are allowed to eat at the same time to ensure that at least one philosopher can eat, and eventually the two chopsticks he used will be released, so that more philosophers can eat. Set a semaphore r with an initial value of 4, and only allow 4 philosophers to take the left chopsticks at the same time, so as to ensure that at least one philosopher can eat without starvation and deadlock.
semaphore chopstick[5]={1,1,1,1,1};
semaphore r=4;
void philosopher(int i)
{
while(True)
{
think();
wait(r);
wait(chopstick[i]);
wait(chopstick[i+1]%5);
eat();
signal(chopstick[i+1]%5);
signal(chopstick[i]);
signal(r);
think()
}
}

Please login to reply. Login

Reversion History

Loading...
No reversions found.