Dining Problem 2
Dining Problem 2
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
int main()
{
int i,a[5];
pthread_t tid[5]; // creation of threads refering to 5 philosophers
for(i=0;i<5;i++)
sem_init(&chopstick[i],0,1); //initializations of binary semaphore .
for(i=0;i<5;i++){
a[i]=i;
pthread_create(&tid[i],NULL,philosopher,(void *)&a[i]); // creation of philosopher and
assigning it a number.
}
for(i=0;i<5;i++)
pthread_join(tid[i],NULL); // waits until a thread gets terminated
}
eat(phil);
sleep(2);
printf("\nPhilosopher %d has finished eating",phil);
int main()
{
// Define counter var i and status_message
int i, status_message;
void *msg;
// Wait for all philosophers threads to complete executing (finish dining) before
closing the program
for (i = 1; i <= NUM_PHILOSOPHERS; i++)
{
status_message = pthread_join(philosopher[i], &msg);
if (status_message != 0)
{
printf("\n Thread join failed \n");
exit(1);
}
}