about dining philosopher problem

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
Last edited on
Is there a particular reason to study pthreads, even though the current C++ standard offers threading?
See http://www.cplusplus.com/reference/multithreading/


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).
just wanna study more about this topic from my original source code

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

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

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;
}
and wanna know about how to use c++

is your priority learning C++ or pthreads? Because I don't see any C++ in your code.
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++
Topic archived. No new replies allowed.