/* ********************************************************************** */ /* * * */ /* * dine.c * */ /* * * */ /* ********************************************************************** */ /* * * */ /* * Homework #3 - Problem #1 * */ /* * * */ /* * This program is designed to demonstrate the use of pthreads to * */ /* * solve the dining philosophers problem. * */ /* * * */ /* ********************************************************************** */ /* * * */ /* * 07/18/2010 - Program Created * */ /* * * */ /* ********************************************************************** */ #include #include #include #include #define PHILOSOPHERS 5 #define MAXTIME 10.0 #define EATING 0 #define THINKING 1 #define HUNGRY 2 #define TRUE 1 #define FALSE 0 pthread_mutex_t chopsticks[PHILOSOPHERS]; int done = FALSE; /* ********************************************************************** */ /* * * */ /* * philosohper: This function implements a philosopher thread which * */ /* * will alternate between eating and thinking for random times. * */ /* * * */ /* ********************************************************************** */ void *philosopher(arg) void *arg; { int state; int sleeptime; int left, right; int count = 0; /* Determine which chopsticks are next to us */ left = (int) arg - 1; if (left < 0) left = PHILOSOPHERS - 1; right = (int) arg; fprintf(stderr, "Starting Phil %d with left = %d, right = %d\n", arg, left, right); /* Main loop */ while (!done) { state = THINKING; sleeptime = 1 + (int)(rand()*MAXTIME/(RAND_MAX+1.0)); fprintf(stderr, "Phil %d is THINKING for %d\n", arg, sleeptime); sleep(sleeptime); state = HUNGRY; fprintf(stderr, "Phil %d is HUNGRY\n", arg); pthread_mutex_lock(&chopsticks[left]); fprintf(stderr, "Phil %d got left %d\n", arg, left); pthread_mutex_lock(&chopsticks[right]); fprintf(stderr, "Phil %d got right %d\n", arg, right); state = EATING; sleeptime = 1 + (int)(rand()*MAXTIME/(RAND_MAX+1.0)); fprintf(stderr, "Phil %d is EATING for %d, count = %d\n", arg, sleeptime, count); sleep(sleeptime); pthread_mutex_unlock(&chopsticks[left]); pthread_mutex_unlock(&chopsticks[right]); count++; if (count > 5) break; } pthread_exit(NULL); } int main(argc, argv) int argc; char **argv; { int i, array[PHILOSOPHERS]; pthread_t *t; if (argc != 1) { fprintf(stderr, "usage: %s\n", argv[0]); exit(1); } /* Seed the random number generator */ srand(time(0)); /* Initialize the mutex variables */ for (i = 0; i < PHILOSOPHERS; i++) pthread_mutex_init(&chopsticks[i], NULL); t = (pthread_t *) malloc(sizeof(pthread_t) * PHILOSOPHERS); /* Start the threads and wait for them to complete */ for (i = 0; i < PHILOSOPHERS; i++) { array[i] = i; pthread_create(&t[i], NULL, philosopher, (void *) array[i]); } for (i = 0; i < PHILOSOPHERS; i++) { pthread_join(t[i], NULL); } }