i am self-practicing this problem right now, and wanna know about how to use c++(in linux) and using the conditional variables provided by the pthreads api.(using monitor)also, it must be free of the race condition able to handle five philosophers. so i want to get some reference source code to have a look
The C++ is standard, and thus the same on all (supported) platforms. Programming tools are similar. OS API's do differ though. For example, how dynamic libraries are handled (.so, .dll, .dylib).
int state = THINKING;
int left = (id + peopleno - 1) % peopleno;
int right = (id + 1) % peopleno;
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\n",right);
}
}else{
printf("Philosopher left forks is busy,left=%d\n",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)\n",left,right);
sem_post(&forks[left]);
sem_post(&forks[right]);
printf("Philosopher release left and right forks: (%d,%d)\n",left,right);
usleep(500);
state = THINKING;
strcpy(pstate,"Thinking after eat");
break;
}
pthread_mutex_lock(&mutex);
printf("Philosopher is %s\n",pstate);
pthread_mutex_unlock(&mutex);
usleep(1000);
}
pthread_exit((void*)0);
}
int main(){
pthread_t a[peopleno];
int i;
pthread_mutex_init(&mutex,NULL);
for(i = 0 ; i < peopleno ; i ++){
sem_init(&forks[i],0,1);
}
for(i = 0 ; i < peopleno ; i ++){
pthread_create(&a[i],NULL,philosopher,(void*)i);
}
for(i = 0 ; i < peopleno ; i ++){
pthread_join(a[i],NULL);
}
return 0;
}
To rewrite this code in c++ and have the above features. Therefore, just wanna to get some reference to add the above features and rewrite this code in c++