Can someone rewrite the code for the Dining Philosophers pro

Can someone rewrite the code for the Dining Philosophers problem so that it follows the directions given? Otherwise the current Expert Answer is not helpful. The URL is http://www.chegg.com/homework-help/questions-and-answers/dining-philosophers-c-create-cygwin-unix-console-program-implements-solution-dining-philos-q8194649

Solution

I have rewrite the code as below:

#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#define THINKING 0
#define HUNGRY 1
#define EATING 2
#define N 5
sem_t forks[N];
pthread_mutex_t mutex;

void *philosopher(void *arg){
int id = (int) arg;

int state = THINKING;
int left = (id + N - 1) % N;
int right = (id + 1) % N;
char pstate[32];

while(1){
switch(state){
case HUNGRY:
strcpy(pstate,\"Hungry\");
if(sem_wait(&forks[left]) == 0){
if(sem_trywait(&forks[right]) == 0){
strcpy(pstate,\"I will Eating\");
state = EATING;
}else{
state = THINKING;
strcpy(pstate,\"I have not forks\");
sem_post(&forks[left]);
printf(\"Philosopher right forks is busy,right=%d\ \",right);
}
}else{
printf(\"Philosopher left forks is busy,left=%d\ \",left);
}
break;
case THINKING:
usleep(300);
state = HUNGRY;
strcpy(pstate,\"Thinking before eat\");
break;
case EATING:
printf(\"Philosopher fetch left and right forks: (%d,%d)\ \",left,right);
sem_post(&forks[left]);
sem_post(&forks[right]);
printf(\"Philosopher release left and right forks: (%d,%d)\ \",left,right);
usleep(500);
state = THINKING;
strcpy(pstate,\"Thinking after eat\");
break;
}
pthread_mutex_lock(&mutex);
printf(\"Philosopher is %s\ \",pstate);
pthread_mutex_unlock(&mutex);
usleep(1000);
}

pthread_exit((void*)0);
}

int main(){
pthread_t a[N];
int i;
pthread_mutex_init(&mutex,NULL);
for(i = 0 ; i < N ; i ++){
sem_init(&forks[i],0,1);
}
for(i = 0 ; i < N ; i ++){
pthread_create(&a[i],NULL,philosopher,(void*)i);
}
for(i = 0 ; i < N ; i ++){
pthread_join(a[i],NULL);
}
return 0;
}

Can someone rewrite the code for the Dining Philosophers problem so that it follows the directions given? Otherwise the current Expert Answer is not helpful. Th
Can someone rewrite the code for the Dining Philosophers problem so that it follows the directions given? Otherwise the current Expert Answer is not helpful. Th

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site