Professional Documents
Culture Documents
// eat
signal (chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
// think
} while (TRUE);
Program
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
# define EATINGTIME 1
pthread_create(&t1,&at1,philosopher1,NULL);
pthread_create(&t2,&at1,philosopher2,NULL);
pthread_create(&t3,&at1,philosopher3,NULL);
pthread_create(&t4,&at1,philosopher4,NULL);
pthread_create(&t5,&at1,philosopher5,NULL);
while(end!=5)
{
}
}
/*definition of philosopher1.*/
void * philosopher1()
{
int i=0;
printf("\n\t\tPHILOSOPHER-1 THINKING.\n");
while(i<EATINGTIME)
{
sleep(1);
/*waiting to acquire the forks.*/
sem_wait(&sem_1);
sem_wait(&sem_2);
printf("\n\t\t\t* PHILOSOPHER-1 EATING.*\n");
sleep(1);
/*releasing the forks*/
sem_post(&sem_1);
sem_post(&sem_2);
printf("\n\t\tPHILOSOPHER-1 THINKING.\n");
i++;
}
end++;
}
/*philosopher2.*/
void * philosopher2()
{
int i=0;
printf("\n\t\tPHILOSOPHER-2 THINKING.\n");
while(i<EATINGTIME)
{
sleep(1);
sem_wait(&sem_2);
sem_wait(&sem_3);
printf("\n\t\t\t* PHILOSOPHER-2 EATING.*\n");
sleep(1);
sem_post(&sem_2);
sem_post(&sem_3);
printf("\n\t\tPHILOSOPHER-2 THINKING.\n");
i++;
}
end++;
}
/*philosopher 3*/
void * philosopher3()
{
int i=0;
printf("\n\t\tPHILOSOPHER-3 THINKING.\n");
while(i<EATINGTIME)
{
sleep(1);
sem_wait(&sem_3);
sem_wait(&sem_4);
printf("\n\t\t\t* PHILOSOPHER-3 EATING.*\n");
sleep(1);
sem_post(&sem_3);
sem_post(&sem_4);
printf("\n\t\tPHILOSOPHER-3 THINKING.\n");
i++;
}
end++;
}
/*philosopher 4.*/
void * philosopher4()
{
int i=0;
printf("\n\t\tPHILOSOPHER-4 THINKING.\n");
while(i<EATINGTIME)
{
sleep(1);
sem_wait(&sem_4);
sem_wait(&sem_5);
printf("\n\t\t\t* PHILOSOPHER-4 EATING.*\n");
sleep(1);
sem_post(&sem_4);
sem_post(&sem_5);
printf("\n\t\tPHILOSOPHER-4 THINKING.\n");
i++;
}
end++;
}
/*philosopher 5.*/
void * philosopher5()
{
int i=0;
printf("\n\t\tPHILOSOPHER-5 THINKING.\n");
while(i<EATINGTIME)
{
sleep(1);
sem_wait(&sem_5);
sem_wait(&sem_1);
printf("\n\t\t\t* PHILOSOPHER-5 EATING.*\n");
sleep(1);
sem_post(&sem_5);
sem_post(&sem_1);
printf("\n\t\tPHILOSOPHER-5 THINKING.\n");
i++;
}
end++;
}