Deadlock Avoidance Using Semaphores: Implement the deadlock-free solution to Dining Philosophers problem to illustrate the problem of deadlock and/or starvation that can occur when many synchronized threads are competing for limited resources.

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

pthread_t philosopher[5];
pthread_mutex_t spoon[5];

void *func(int n)
{
 printf("Philosopher %d is thinking\n",n);
 pthread_mutex_lock(&spoon[n]);
 pthread_mutex_lock(&spoon[(n+1)%5]);
 printf("Philosopher %d is eating\n",n);
 sleep(3);
 pthread_mutex_unlock(&spoon[n]);
 pthread_mutex_unlock(&spoon[n+1]);
 printf("Philosopher %d finished eating\n",n);
 return(NULL); 
}

int main()
{
 int i;
 for(i=0;i<5;i++)
  pthread_mutex_init(&spoon[i],NULL);
 for(i=0;i<5;i++)
  pthread_create(&philosopher[i],NULL,(void *)func,(void *)i);
 for(i=0;i<5;i++)
  pthread_join(philosopher[i],NULL);
 for(i=0;i<5;i++)
  pthread_mutex_destroy(&spoon[i]);
 return 0;
}

/*
OUTPUT

[email protected]:~/Desktop/os/4$ gcc os4.c -lpthread -o p
[email protected]:~/Desktop/os/4$ ./p
Philosopher 0 is thinking
Philosopher 1 is thinking
Philosopher 1 is eating
Philosopher 3 is thinking
Philosopher 3 is eating
Philosopher 4 is thinking
Philosopher 2 is thinking
Philosopher 1 finished eating
Philosopher 0 is eating
Philosopher 3 finished eating
Philosopher 2 is eating
Philosopher 0 finished eating
Philosopher 2 finished eating
Philosopher 4 is eating
Philosopher 4 finished eating
[email protected]:~/Desktop/os/4$

*/
Deadlock Avoidance Using Semaphores: Implement the deadlock-free solution to Dining Philosophers problem to illustrate the problem of deadlock and/or starvation that can occur when many synchronized threads are competing for limited resources. Deadlock Avoidance Using Semaphores: Implement the deadlock-free solution to Dining Philosophers problem to illustrate the problem of deadlock and/or starvation that can occur when many synchronized threads are competing for limited resources. Reviewed by Huzaif Sayyed on April 17, 2017 Rating: 5

1 comment:

  1. Hello good programmer.
    In this code there is an warning occurring on pthread_create(&philosopher[i],NULL,(void *)func,(void *)i);

    the warning is;

    warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] pthread_create(&philosopher[i],NULL,(void *)func,(void *)i);

    can you tell how can i fix this error.
    Thanks in advance.

    ReplyDelete

Powered by Blogger.