#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<sys/types.h>
#include<sys/stat.h>
#define N 5
#define LEFT (N+n-1)%N
#define RIGHT (n+1)%N
enum{thinking,eating,hungry};
int philstate[N];
sem_t s[N],mutex;
void think(int n)
{ sleep(1);
}
void test(int n)
{
if(philstate[LEFT]!=eating && philstate[RIGHT]!=eating)
{
philstate[n]=eating;
sem_post(s+n);
}
sem_post(&mutex);
}
void getforks(int n)
{
sem_wait(&mutex);
philstate[n]=hungry;
printf("\n PHILOSOPHER %d IS HUNGRY ",n);
sleep(1);
test(n);
sem_post(&mutex);
sem_wait(s+n);
}
void eat(int n)
{
int i;
for(i=0;i<4;i++)
{
printf("\n PHILOSOPHER %d IS EATING",n);
sleep(1);
}
printf("\nPHILOSOPHER %d HAS STOPPED EATING",n);
sleep(1);
}
void putforks(int n)
{
sem_wait(&mutex);
philstate[n]=thinking;
printf("\n PHILOSOPHER %d IS THINKING.",n);
sleep(1);
test(LEFT);
test(RIGHT);
sem_post(&mutex);
}
void *phil(void *argc)
{
int p;
p=atoi(argc);
printf("\n PHILOSOPHER %d:\n",p);
while(1)
{
think(p);
getforks(p);
eat(p);
putforks(p);
}
}
main()
{
sem_init(&mutex,0,1);
int i;
for(i=0;i<5;i++)
sem_init(&s[i],0,0);
pthread_t t1,t2,t3,t4,t5;
pthread_create(&t1,0,phil,"0");
pthread_create(&t2,0,phil,"1");
pthread_create(&t3,0,phil,"2");
pthread_create(&t4,0,phil,"3");
pthread_create(&t5,0,phil,"4");
while(1);
}
OUTPUT
./a.out
No comments:
Post a Comment