Hello,
I'm givin' the Dining Phiolsophers a try to solve it with Mutexs but it's not going to well.
The Mutex initalisation works, the threads start, the VOID Philosopher must be correct since I translated it from the structure which is in the book I'm reading.
So it has to be something in the main class are my thaughts.
Code:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <semaphore.h>
pthread_mutex_t chopsticks[5] = PTHREAD_MUTEX_INITIALIZER;
void *Philosopher(void *arg);
struct Param {
int index;
};
int main(void)
{
pthread_t phil0, phil1, phil2, phil3, phil4;
int i;
struct Param p[5];
for(i=0; i<5; i++)
{
if (pthread_mutex_init(&chopsticks[i],0) != 0)
{
printf("Mutex_Init Error\n");
}
p[i].index=i;
}
if( pthread_create(&phil0, NULL, Philosopher, &p[0]) ||
pthread_create(&phil1, NULL, Philosopher, &p[1]) ||
pthread_create(&phil2, NULL, Philosopher, &p[2]) ||
pthread_create(&phil3, NULL, Philosopher, &p[3]) ||
pthread_create(&phil4, NULL, Philosopher, &p[4]) )
{
printf("Threads Fail\n");
exit(EXIT_FAILURE);
}
for(i=0; i<5; i++)
{
pthread_mutex_destroy(&chopsticks[i]);
}
pthread_exit(NULL);
exit(0);
}
void *Philosopher(void *arg)
{
struct Param *p = (struct Param*)arg;
int index=p->index;
do{
pthread_mutex_lock(&chopsticks[index]);
pthread_mutex_lock(&chopsticks[(index+1)%5]);
// eat
printf("Philosopher %d is eating \n", index);
pthread_mutex_unlock(&chopsticks[index]);
pthread_mutex_unlock(&chopsticks[(index+1)%5]);
// think
printf("Philosopher %d is thinking \n", index);
sleep(1);
}while(1);
}
The output I experience:
Code:
Philosopher 0 is eating
Philosopher 0 is thinking
Philosopher 2 is eating
Philosopher 1 is eating
Philosopher 1 is thinking
Philosopher 4 is eating
Philosopher 3 is eating
Philosopher 3 is thinking
Philosopher 2 is thinking
Philosopher 4 is thinking
Philosopher 0 is eating
Philosopher 0 is thinking
Philosopher 1 is eating
Also please say why my reasoning is wrong, I'm trying to clean constantly.
Kind regards