Friday 1 July 2016

Dining Philosopher Problem in C (Operating Systems)

Dining Philosopher Problem in C (Operating Systems)

Description: The following C code solves the Dining Philosopher problem using semaphore. It’s a simple Dining Philosopher problem solution often taught in Operating Systems.


#include<stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>

#define SIZE 5

sem_t chopsticks[SIZE];
sem_t isEating[SIZE];

void *Philosopher(void *param){
   int i,s;

   while(1){
      i=rand()%5;
      sem_wait(&isEating[i]);
      printf("\n\n\t--> Philosopher#%d Turn\n\n",i);
      if(i%2){
          sem_wait(&chopsticks[i]);
          sem_wait(&chopsticks[(i+1)%5]);
      }
      else{
          sem_wait(&chopsticks[(i+1)%5]);
          sem_wait(&chopsticks[i]);
      }

      printf("--> Philosopher#%d has STARTED Eating\n",i);

      s=rand()%4+1;
      sleep(s);

      printf("--> Philosopher#%d has FINISHED Eating\n",i);

      sem_post(&chopsticks[i]);
      sem_post(&chopsticks[(i+1)%5]);
      sem_post(&isEating[i]);
   }
}

int main(){
   int i;
   for(i=0;i<SIZE;i++)
      sem_init(&chopsticks[i], 2, 1);

   for(i=0;i<SIZE;i++)
      sem_init(&isEating[i], 2, 1);

   pthread_t threadID;
   pthread_attr_t attributes;
   pthread_attr_init (&attributes);


   for(i=0;i<4;i++)
      pthread_create(&threadID,&attributes,Philosopher,NULL);

   sleep(30);
   exit(0);
}

No comments

Post a Comment

Recent Posts