/* * File: main.c * Author: rshe005 * * Simplistic Dining Philosophers program with a pseudo * simultaneous wait on the forks. * * Created on 12 August 2009, 3:41 PM * Revised 18 August 2015 */ #include #include #include #include #include #include #define NUM_PHILOSOPHERS 5; typedef struct philos { char *status; pthread_mutex_t *right, *left; } Philosopher; void philosopherSetup(Philosopher *philosopher, pthread_mutex_t *left, pthread_mutex_t *right) { philosopher->left = left; philosopher->right = right; } void *philosopherRun(void *phil) { Philosopher *philosopher = phil; while (true) { philosopher->status = "thinking"; philosopher->status = "waiting"; bool both = false; do { if (pthread_mutex_lock(philosopher->left) != 0) fprintf(stderr, "Left lock error.\n"); int right_lock_result = pthread_mutex_trylock(philosopher->right); switch (right_lock_result) { case 0: both = true; break; case EBUSY: pthread_mutex_unlock(philosopher->left); // try again both = false; break; default: fprintf(stderr, "Right lock error\n."); } } while (!both); printf("."); // this won't appear if blocked philosopher->status = "eating"; sleep(1); pthread_mutex_unlock(philosopher->left); pthread_mutex_unlock(philosopher->right); } } /* * Starts all of the philosopher threads and reports on their progress. */ int main(int argc, char** argv) { int number = NUM_PHILOSOPHERS; if (argc > 1) { number = atoi(argv[1]); } printf("Creating %d philosophers.\n", number); Philosopher philosophers[number]; pthread_mutex_t forks[number]; pthread_t threads[number]; int i; for (i = 0; i < number; i++) { // create the locks if (pthread_mutex_init(&forks[i], NULL)) { fprintf(stderr, "Unable to create locks.\n"); return (EXIT_FAILURE); } } for (i = 0; i < number; i++) { // setup the philosophers philosopherSetup(&philosophers[i], &forks[i], &forks[(i + 1) % number]); } for (i = 0; i < number; i++) { // create and start the threads pthread_create(&threads[number], NULL, philosopherRun, &philosophers[i]); } while (true) { sleep(1); for (i = 0; i < number; i++) { usleep(1000); printf("%d: %-8s ", i, philosophers[i].status); } printf("\n"); } return (EXIT_SUCCESS); }