Aim: 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<semaphore.h>
#include<pthread.h>
#include<unistd.h>
#define N 5
#define THINKING
0
#define HUNGRY
1
#define EATING
2
#define Left
(ph_num+4)%N
#define Right
(ph_num+1)%N
sem_t room;
sem_t chopst[N];
void *philospher(void *num);
void take_chopst(int);
void put_chopst(int);
void test(int);
int state[N];
int phil_num[N]={0,1,2,3,4};
int main()
{
int i;
pthread_t thread_id[N];
sem_init(&room,0,1);
for(i=0;i<N;i++)
sem_init(&chopst[i],0,0);
for(i=0;i<N;i++)
{
pthread_create(&thread_id[i],NULL,philospher,&phil_num[i]);
printf("philospher %d is thinking \n
",i+1);
}
for(i=0;i<N;i++)
{
pthread_join(thread_id[i],NULL);
sem_destroy(&chopst[N]);
sem_destroy(&room);
pthread_exit(0);
}
}
void *philospher(void *num)
{
int x=1;
while(x<5)
{
int *i=num;
usleep(1);
take_chopst(*i);
usleep(1);
put_chopst(*i);
x++;
}
}
void take_chopst(int ph_num)
{
sem_wait(&room);
state[ph_num]=HUNGRY;
printf("philospher %d is hungry
\n",ph_num+1);
test(ph_num);
sem_post(&room);
sem_wait(&chopst[ph_num]);
}
void test(int ph_num)
{
if(state[ph_num]==HUNGRY &&
state[Left]!=EATING && state[Right]!=EATING)
{
state[ph_num]=EATING;
usleep(1);
printf("philospher %d takes left chopst
%d and right chopst %d\n",ph_num+1,Left+1,ph_num+1);
printf("philospher %d is Eating
\n",ph_num+1);
sem_post(&chopst[ph_num]);
}
}
void put_chopst(int ph_num)
{
sem_wait(&room);
state[ph_num]=THINKING;
printf("philospher
%d is putting left chopst %d and right chopst %d
down\n",ph_num+1,Left+1,ph_num+1);
printf("Philospher
%d is thinking \n",ph_num+1);
test(Left);
test(Right);
sem_post(&room);
}
No comments:
Post a Comment