Question
Number of philosophers = 5, number of chopsticks = 5, number of worker threads = 5 (you may use an additional worker thread to print
Number of philosophers = 5, number of chopsticks = 5, number of worker threads = 5 (you may use an additional worker thread to print information about current state of philosophers with some interval)
The program should run infinitely and output information about beginning of current actions of philosophers along with current states of philosophers (THINKING, EATING, HUNGRY if applicable)
Implement a deadlock-free solution for Dining Philosophers Problem using monitors and condition variables (only monitors with condition variables can be used). Attach a source code here along with few lines of output
Here is the code so far:
#include
pthread_t phil[5]; pthread_mutex_t fork[5];
void *func(int n) { printf ("Philosopher %d is thinking ",n);
//when philosopher 5 is eating he takes fork 1 and fork 5 pthread_mutex_lock(&fork[n]); pthread_mutex_lock(&fork[(n+1)%5]); printf ("Philosopher %d is eating ",n); sleep(3); pthread_mutex_unlock(&fork[n]); pthread_mutex_unlock(&fork[(n+1)%5]);
printf ("Philosopher %d hungry ",n);
return(NULL); }
int main() { int i; for(i=0;i<5;i++) pthread_mutex_init(&fork[i],NULL);
for(i=0;i<5;i++) pthread_create(&phil[i],NULL,(void *)func,(void *)i);
for(i=0;i<5;i++) pthread_join(phil[i],NULL);
for(i=0;i<5;i++) pthread_mutex_destroy(&fork[i]);
return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started