Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dining philosophers problem
#include<stdlib.h>
#include<stdio.h>
#include<pthread.h>
pthread_mutex_t *forks;
pthread_t * philosophers;
pthread_mutex_t output_lock;
int nb_philosopher = 5;
int take(int philosopher, int fork) {
pthread_mutex_lock(&output_lock);
int ret = pthread_mutex_trylock(&forks[fork]);
if(ret == 0)
printf("Philosopher %i takes fork %i\n", philosopher, fork);
else
printf("Philosopher %i can not take fork %i\n", philosopher, fork);
pthread_mutex_unlock(&output_lock);
pthread_yield();
return ret;
}
void release(int philosopher, int fork) {
pthread_mutex_lock(&output_lock);
pthread_mutex_unlock(&forks[fork]);
printf("Philosopher %i releases fork %i\n", philosopher, fork);
pthread_mutex_unlock(&output_lock);
pthread_yield();
}
void eat(int philosopher) {
pthread_mutex_lock(&output_lock);
printf("Philosopher %i eats\n", philosopher);
pthread_mutex_unlock(&output_lock);
}
void philosopher(int id) {
for(;;)
if (take(id, id) == 0) {
if(take(id, (id + 1)%nb_philosopher) == 0) {
eat(id);
release(id, (id + 1) % nb_philosopher);
release(id, id);
return;
}
release(id, id);
}
}
int main(int argc, char* argv[]) {
nb_philosopher = atoi(argv[1]);
forks = malloc(nb_philosopher * sizeof(pthread_mutex_t));
philosophers = malloc(nb_philosopher * sizeof(pthread_t));
for (int i = 0; i < nb_philosopher; i++) {
pthread_create(&philosophers[i], NULL, &philosopher, i);
}
for (int i = 0; i < nb_philosopher; i++) {
pthread_join(philosophers[i], NULL);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.