World's most popular travel blog for travel bloggers.

MCS-041 Solved Assignment (Question 3)

, , No Comments

The Dinning-philosopher Problem


Five philosophers sit around a circular table. Each philosopher spends his life alternatively thinking and eating. In the center of the table is a large bowl of rice. A philosopher needs two chopsticks to eat. Only 5 chop sticks are available and a chopstick is placed between each pair of philosophers. They agree that each will only use the chopstick to his immediate right and left.

From time to time, a philosopher gets hungry and tries to grab the two chopsticks that are immediate left and right to him.When a hungry philosopher has both his chopsticks at the same time, he eats without releasing his chopsticks. When he finishes eating, he puts down both his chopsticks and starts thinking again.

Here’sa solution for the problemwhich does not require a process towrite another process’s state, and gets equivalent parallelism.

#define N 5  /* Number of philosphers */
#define RIGHT(i) (((i)+1) %N)

#define LEFT(i) (((i)==N) ? 0 : (i)+1)
typedef enum { THINKING, HUNGRY, EATING } phil_state;
phil_state state[N];
semaphore mutex =1;
semaphore s[N]; 

/* one per philosopher, all 0 */
void get_forks(int i) {
         state[i]= HUNGRY;
         while ( state[i] == HUNGRY ) {
            P(mutex);
               if ( state[i]== HUNGRY &&
                    state[LEFT] != EATING &&
                    state[RIGHT(i)] != EATING) {
                   state[i]= EATING;
                   V(s[i]);
               }
      V(mutex);
     P(s[i]);
 }
}
void put_forks(int i) {
       P(mutex);
      state[i]=THINKING;
      if ( state[LEFT(i)]== HUNGRY ) V(s[LEFT(i)]);
      if ( state[RIGHT(i)]== HUNGRY) V(s[RIGHT(i)]);
       V(mutex);
      } 

void philosopher(int process) {
       while(1) {
             think();
            get_forks(process);
            eat();
            put_forks();
   }

0 comments:

Post a Comment

Let us know your responses and feedback