From b12791a169f25a576cd612b2c881dc0c7c5bdeb3 Mon Sep 17 00:00:00 2001 From: chyyuu Date: Tue, 10 May 2016 09:58:59 +0800 Subject: [PATCH] add user app for philosopher with semaphore, pthread, etc. --- .../philosophers-with-semaphore.c | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 related_info/lab7/semaphore_condition/philosophers-with-semaphore.c diff --git a/related_info/lab7/semaphore_condition/philosophers-with-semaphore.c b/related_info/lab7/semaphore_condition/philosophers-with-semaphore.c new file mode 100644 index 0000000..f4876b3 --- /dev/null +++ b/related_info/lab7/semaphore_condition/philosophers-with-semaphore.c @@ -0,0 +1,63 @@ +/* Philosophers.c - Demonstrate the semaphore solution to the dining + philosophers problem. The Room semaphore is neede to prevent all + philosophers from entering the room and grabbing their left most fork + at the same time, which would lead to deadlock. The Room sempahore + can be enabled by specifying a command line argument. */ + +#include +#include +#include +typedef enum { False=0, True=1 } bool ; + +#define N 5 /* Number of times each philosopher tries to eat */ +#define P 3 /* Number of philosophers */ + +sem_t Room; +sem_t Fork[P]; +bool Switch ; + +void *tphilosopher(void *ptr) { + int i, k = *((int *) ptr); + for(i = 1; i <= N; i++) { + printf("%*cThink %d %d\n", k*4, ' ', k, i); + if(Switch) { + sem_wait(&Room) ; + } + sem_wait(&Fork[k]) ; + sem_wait(&Fork[(k+1) % P]) ; + printf("%*cEat %d %d\n", k*4, ' ', k, i); + sem_post(&Fork[k]) ; + sem_post(&Fork[(k+1) % P]) ; + if(Switch) { + sem_post(&Room) ; + } + } + pthread_exit(0); +} + +int main(int argc, char * argv[]) { + int i, targ[P]; + pthread_t thread[P]; + sem_init(&Room, 0, P-1); + Switch = (argc > 1); /* Room semaphore on/off */ + printf("Switch=%s\n",(Switch?"true":"false")); + for(i=0;i