Professional Documents
Culture Documents
Operating Systems Homework
Operating Systems Homework
The philosophers never speak to each other, which creates a dangerous possibility
of deadlock. The deadlock could occur if every philosopher holds a left chopstick
and waits perpetually for a right chopstick (or vice versa).
Figure 1
the story of the dining philosophers as an exercise in concurrent programming in the
early 1970s.
this problem has attracted and challenged both theoreticians and programmers, and
a variety of different solutions have been developed, most of them using some kind
of synchronization mechanism (typically a semaphore) to control accesses to
chopsticks by hungry philosophers.
Figure 2
Solution 1: semaphore
Each philosopher picks up first the fork on the left and then the fork on the right.
After the philosopher is finished eating, the two forks are replaced on the table.
Figure 3
If all of the philosophers are hungry at the same time, they all sit down, they all pick
up the fork on their left, and they all reach out for the other fork, which is not there.
We could consider adding an attendant who only allows four philosophers at a time
into the dining room.
With at most four seated philosophers at least one philosopher will have access to
two forks.
//*program diningphilosophers * //
Semaphore fork [ 5 ] = { 1 } ;
Semaphore room = { 4 } ;
int i ;
Void philosopher ( int i )
{
While ( true ) {
Think () ;
Wait ( room );
Wait ( fork [ i ] ) ;
Wait ( fork [ ( i + 1 ) mod 5 ] ) ;
eat ( ) ;
Signal ( fork [ ( i + 1 ) mod 5 ] ) ;
Signal ( fork [ i ] ) ;
Signal (room) ;
}
}
Void main ()
{
Parbegin ( philosopher (0) , philosopher ( 1) , philosopher (2) ,
philosopher (3) , philosopher (4) ;
Figure 4
ID: 558