Tuesday, April 26, 2011

Dining-Philosophers Problem

This one springs from Ash(es)... ;)

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

sem_t f[5],r;
void philosopher(void * i)
{
  int *p = (int*)i;
  while(1)
    {
    printf("\nphilosopher %d is Thinking",*p);
    sleep(2);
    sem_wait(&r);
    sem_wait(&f[*p]);
      sem_wait(&f[(*p+1)%5]);
      printf("\nPhilosopher %d eating",*p);
      sleep(5);
      sem_post(&f[(*p+1)%5]);
      sem_post(&f[*p]);
    sem_post(&r);
    }
    }


int main()
{
  pthread_t ph[5];
  pthread_attr_t *a = NULL;
  int p[] ={0,1,2,3,4};
  int i;
  sem_init(&r,0,4);
  for(i=0;i<5;i++)
    sem_init(&f[i],0,1);
  pthread_create(&ph[0],a,philosopher,(void *)&p[0]);
  pthread_create(&ph[1],a,philosopher,(void *)&p[1]);
  pthread_create(&ph[2],a,philosopher,(void *)&p[2]);
  pthread_create(&ph[3],a,philosopher,(void *)&p[3]);
  pthread_create(&ph[4],a,philosopher,(void *)&p[4]);
 
  for(i=0;i<5;i++)
    pthread_join(ph[i],NULL);
  return 0;
}

1 comment: