Philosophers spend their lives thinking and eating . These Philosophers don’t in
ID: 3723237 • Letter: P
Question
Philosophers spend their lives thinking and eating . These Philosophers don’t interact with their neighbors, occasionally try to pick up 2 chopsticks (one at a time) to eat from bowl and they need both to eat, then release both when done
In the case of 5 philosophers, Semaphore chopstick [5] initialized to 1
Does the following codes have problem? If so, which kind(s) problem(s)? How to deal with the problem(s)?
do {
wait (chopstick[i] );
wait (chopStick[ (i + 1) % 5] );
// eat
signal (chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
// think
} while (TRUE);
Explanation / Answer
Solution:
The given code is:
do {
wait (chopstick[i] );
wait (chopStick[ (i + 1) % 5] );
// eat
signal (chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
// think
} while (TRUE);
The problem with the above code is that it will lead to a deadlock.
In the above code
wait (chopstick[i] ); is making sure that when a philosopher is picking a chopstick everyone else has to wait
wait (chopStick[ (i + 1) % 5] );, but here what may happen is that if two philosophers sitting beside pick there chopsticks
for example:
philosopher 1 picks chopStick[1]
and simultaneously philosopher 2 picks chopStick[2], and similarly philosopher 3 and so on
This is a deadlock situation.
I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)