Last active
March 21, 2018 23:35
-
-
Save battila7/a24cdd11730a09f3c5032a6140ec77f5 to your computer and use it in GitHub Desktop.
Dining Philosophers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include <semaphore.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
const int NUMBER_OF_PHILOSOPHERS = 5; | |
const int SEMAPHORE_ACROSS_THREADS = 0; | |
const int FORK_AVAILABLE = 1; | |
sem_t *forks; | |
void *philosopher(void *data); | |
int main(void) | |
{ | |
/* | |
* Initialize resources. | |
*/ | |
pthread_t *philosopher_threads = (pthread_t *)malloc(NUMBER_OF_PHILOSOPHERS * sizeof(pthread_t)); | |
int *philosopher_thread_arguments = (int *)malloc(NUMBER_OF_PHILOSOPHERS * sizeof(int)); | |
forks = (sem_t *)malloc(NUMBER_OF_PHILOSOPHERS * sizeof(sem_t)); | |
for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; ++i) | |
{ | |
sem_init(forks + i, SEMAPHORE_ACROSS_THREADS, FORK_AVAILABLE); | |
} | |
/* | |
* Start threads and wait for them to finish. | |
*/ | |
for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; ++i) | |
{ | |
philosopher_thread_arguments[i] = i; | |
if (pthread_create(philosopher_threads + i, NULL, philosopher, (void *)(philosopher_thread_arguments + i))) | |
{ | |
return -1; | |
} | |
} | |
for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; ++i) | |
{ | |
int *r; | |
pthread_join(philosopher_threads[i], (void *) &r); | |
printf("Philosopher #%d has exited.\n", *r); | |
} | |
/* | |
* Free all resources. | |
*/ | |
for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; ++i) | |
{ | |
sem_destroy(forks + i); | |
} | |
free(forks); | |
free(philosopher_thread_arguments); | |
free(philosopher_threads); | |
return 0; | |
} | |
void *philosopher(void *data) | |
{ | |
const int identifier = *(const int *)data; | |
printf("Philosopher #%d is ready.\n", identifier); | |
fflush(stdout); | |
for (;;) | |
{ | |
sem_t *lower_fork = forks + identifier; | |
sem_t *upper_fork = forks + ((identifier + 1) % NUMBER_OF_PHILOSOPHERS); | |
sem_wait(lower_fork); | |
sem_wait(upper_fork); | |
printf("Philosopher #%d is eating.\n", identifier); | |
fflush(stdout); | |
sem_post(lower_fork); | |
sem_post(upper_fork); | |
} | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment