#include #include #define N 5 #define BusyEating 1 #define BusyThinking 1 #define Left(p) (p) #define Right(p) (((p)+1) %N) typedef int * semaphore; semaphore chopstick [N]; void signal (semaphore s); void wait (semaphore s); void pick_up (int me) { if (me ==0) { wait (chopstick [Right(me)]); printf ("Philosopher %d picks up right chopstick\n", me); sleep (1); wait (chopstick [Left(me)]); printf ("Philosopher %d picks up left chopstick\n", me); } else { wait(chopstick [Left(me)]); printf ("Philosopher %d, picks up left chopstick\n", me); sleep (1); wait (chopstick[Right(me)]); printf ("Philosopher %d picks up right chopstick\n", me); } } void put_down (int me) { signal (chopstick[Left(me)]); signal (chopstick[Right(me)]); } void philosopher (int me) { char *s; int i=1; for (;;i++) { pick_up (me); s = i == 1 ? "st" : i == 2 ? "nd" : i == 3 ? "rd" : "th"; printf ("Philosopher %d eating for the %d%s time\n", me, i, s); sleep (BusyEating); put_down (me); printf ("Philosopher %s thinking\n", me); sleep (BusyThinking); } } void wait (semaphore s) { int junk; if (read(s[0], &junk, 1) <=0) { printf ("Error: wait failed\n"); exit (1); } } semaphore make_semaphore (void) { int *sema; sema = calloc (2, sizeof (int)); pipe(sema); return; } void signal (semaphore s) { if (write (s[1], "x", 1) <=0) { printf ("Error: write () failed\n"); exit (1); } } main () { int i; for (i = 0; i < N; i++) { chopstick [N] = make_semaphore (); signal (chopstick[i]); } for (i= 0; i < N-1; ++i) { if (fork () == 0) break; } philosopher (i); }