|
| 1 | +/* Philosophers.c - Demonstrate the semaphore solution to the dining |
| 2 | + philosophers problem. The Room semaphore is neede to prevent all |
| 3 | + philosophers from entering the room and grabbing their left most fork |
| 4 | + at the same time, which would lead to deadlock. The Room sempahore |
| 5 | + can be enabled by specifying a command line argument. */ |
| 6 | + |
| 7 | +#include <stdio.h> |
| 8 | +#include <pthread.h> |
| 9 | +#include <semaphore.h> |
| 10 | +typedef enum { False=0, True=1 } bool ; |
| 11 | + |
| 12 | +#define N 5 /* Number of times each philosopher tries to eat */ |
| 13 | +#define P 3 /* Number of philosophers */ |
| 14 | + |
| 15 | +sem_t Room; |
| 16 | +sem_t Fork[P]; |
| 17 | +bool Switch ; |
| 18 | + |
| 19 | +void *tphilosopher(void *ptr) { |
| 20 | + int i, k = *((int *) ptr); |
| 21 | + for(i = 1; i <= N; i++) { |
| 22 | + printf("%*cThink %d %d\n", k*4, ' ', k, i); |
| 23 | + if(Switch) { |
| 24 | + sem_wait(&Room) ; |
| 25 | + } |
| 26 | + sem_wait(&Fork[k]) ; |
| 27 | + sem_wait(&Fork[(k+1) % P]) ; |
| 28 | + printf("%*cEat %d %d\n", k*4, ' ', k, i); |
| 29 | + sem_post(&Fork[k]) ; |
| 30 | + sem_post(&Fork[(k+1) % P]) ; |
| 31 | + if(Switch) { |
| 32 | + sem_post(&Room) ; |
| 33 | + } |
| 34 | + } |
| 35 | + pthread_exit(0); |
| 36 | +} |
| 37 | + |
| 38 | +int main(int argc, char * argv[]) { |
| 39 | + int i, targ[P]; |
| 40 | + pthread_t thread[P]; |
| 41 | + sem_init(&Room, 0, P-1); |
| 42 | + Switch = (argc > 1); /* Room semaphore on/off */ |
| 43 | + printf("Switch=%s\n",(Switch?"true":"false")); |
| 44 | + for(i=0;i<P;i++) { |
| 45 | + sem_init(&Fork[i], 0, 1); |
| 46 | + } |
| 47 | + for(i=0;i<P;i++) { |
| 48 | + targ[i] = i; |
| 49 | + pthread_create(&thread[i], NULL, &tphilosopher,(void *) &targ[i]); |
| 50 | + } |
| 51 | + for(i=0;i<P;i++) { |
| 52 | + pthread_join(thread[i], NULL); |
| 53 | + } |
| 54 | + for(i=0;i<P;i++) { |
| 55 | + sem_destroy(&Fork[i]); |
| 56 | + } |
| 57 | + sem_destroy(&Room); |
| 58 | + return 0; |
| 59 | +} |
| 60 | + |
| 61 | +/* Please note that the checks on the return value of the system calls |
| 62 | + have been omitted to avoid cluttering the code. However, system calls |
| 63 | + can and will fail, in which case the results are unpredictable. */ |
0 commit comments