Write a complete program in c to solve the Dining Philosophe
Write a complete program in c to solve the Dining Philosophers Problem
You may need to do the following:
1. Include the header file semaphore.h
2. Replace the pseudo code of semaphore declaration statements by actual c statements.
3. Implement a main function that
a. initializes the semaphore variables.
b. initialize the state of each philosopher to THINKING.
c. create five philosopher threads with philosopher number 0, 1, 2, 3, 4 respectively. You may want to pass the philosopher number through the parameter of the runner function philosopher().
4. Implement think() and eat() functions. Set each thread to sleep for a random amount of time between 1 and 3 seconds to simulate the amount of time it takes to think() or eat().
5. Output enough messages to screen to indicate the status of each philosopher thread.
6. Time and display how long each philosopher is waiting for obtaining two forks.
Solution
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#define NO_OF_PHILOSOPHERS 5
pthread_t philosophers[NO_OF_PHILOSOPHERS];
pthread_mutex_t mutex_forks = PTHREAD_MUTEX_INITIALIZER;;
int forks[NO_OF_PHILOSOPHERS];
void init()
{
int i;
for(i=0; i<NO_OF_PHILOSOPHERS; i++)
forks[i] = 0;
}
void philosopher(int i)
{
int right = i;
int left = (i - 1 == -1) ? NO_OF_PHILOSOPHERS - 1 : (i - 1);
int locked;
while(1)
{
locked = 0;
while(!locked)
{
pthread_mutex_lock(&mutex_forks);
if(forks[right] || forks[left])
{
pthread_mutex_unlock(&mutex_forks);
printf(\"Philosopher %d cannot take forks. Giving up and thinking.\ \",i);
usleep(random() % 1000); // think.
continue;
}
forks[right] = 1;
forks[left] = 1;
pthread_mutex_unlock(&mutex_forks);
locked = 1;
}
printf(\"Philosopher %d took both forks. Now eating :)\ \",i);
usleep(random() % 500);
printf(\"Philosopher %d done with eating. Giving up forks.\ \",i);
pthread_mutex_lock(&mutex_forks); // give up forks.
forks[right] = 0;
forks[left] = 0;
pthread_mutex_unlock(&mutex_forks);
usleep(random() % 1000);
}
}
int main()
{
init();
int i;
for(i=0; i<NO_OF_PHILOSOPHERS; i++)
pthread_create( &philosophers[i], NULL, philosopher, (void*)i);
for(i=0; i<NO_OF_PHILOSOPHERS; i++)
pthread_join(philosophers[i],NULL);
return 0;
}



