It is a dining philosopher problem.
I used mutual exclusion. No compile error, but it does not work.
I try to print "test" in the route "philosopher",howerver....
Could you help me check what is wrong?
Code:
#include <stdio.h>
#include <pthread.h>
#include <malloc.h>
#include <stdlib.h>
#include <time.h>
#define N 5
struct da {
int id;
};
struct da myda[N];
pthread_mutex_t *mymutex;
void think (int i) {
printf ("\nPhilosopher no. %d is thinking...\n", i);
sleep(2);
}
void eat (int i) {
printf ("\nPhilosopher no. %d is eating...\n", i);
sleep(1);
}
void *philosopher (void *arg)
{
int i;
struct da *mydata;
mydata = (struct da *) arg;
i = mydata->id;
printf("test");//does not execute!
printf("\nPhilosopher %d\n",i);
think(i);
if (i%2 == 1) {
pthread_mutex_lock(&mymutex[i+1]);
pthread_mutex_lock(&mymutex[i]);
eat(i);
pthread_mutex_unlock(&mymutex[i]);
pthread_mutex_unlock(&mymutex[i+1]);
}
else
{
if (i == 4) {
pthread_mutex_lock(&mymutex[i]);
pthread_mutex_lock(&mymutex[0]);
eat(i);
pthread_mutex_unlock(&mymutex[0]);
pthread_mutex_unlock(&mymutex[i]);
}
{
pthread_mutex_lock(&mymutex[i]);
pthread_mutex_lock(&mymutex[i+1]);
eat(i);
pthread_mutex_unlock(&mymutex[i+1]);
pthread_mutex_unlock(&mymutex[i]);
}
}
pthread_exit(NULL);
}
void main (int argc, char*argv[]) {
pthread_t threads[N];
int rc, i;
int *id[N];
/*pthread_t threads[N];*/
mymutex = (pthread_mutex_t*)malloc(sizeof(mymutex) * N);
printf("\nThere are %d philosophers\n", N);
for (i = 0; i<N; i++) {
pthread_mutex_init(&mymutex[i], NULL);
}
for (i = 0; i<N; i++) {
myda[i].id = i;
rc = pthread_create(&threads[i], NULL, philosopher,(void *)&myda[i]);
if (rc) {
printf("ERROR;return code from pthread_create() is %d\n",rc);
exit(-1);
}
}
for (i = 0; i<N; i++) {
pthread_mutex_destroy(&mymutex[i]);
}
}