Skip to content

Instantly share code, notes, and snippets.

@Bromind
Created April 25, 2019 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bromind/3b611ac62676a0c4cf803555d40850c6 to your computer and use it in GitHub Desktop.
Save Bromind/3b611ac62676a0c4cf803555d40850c6 to your computer and use it in GitHub Desktop.
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