1 // Dining philosophers solution with semaphores
11 pthread_mutex_t *left_fork;
12 pthread_mutex_t *right_fork;
17 static void * philosopher_doit(void *forks_arg) {
18 struct forks *forks = forks_arg;
19 sem_wait(forks->sem_dining);
20 pthread_mutex_lock(forks->left_fork);
21 pthread_mutex_lock(forks->right_fork);
23 if(forks->DEBUG) printf("Philosopher %d just ate.\n", forks->philosopher);
25 pthread_mutex_unlock(forks->left_fork);
26 pthread_mutex_unlock(forks->right_fork);
27 sem_post(forks->sem_dining);
31 int main(int argc, char* argv[]) {
33 printf("Usage: %s NUM_PHILOSOPHERS DEBUG\n", argv[0]);
37 int NUM_THREADS = atoi(argv[1]);
38 int DEBUG = atoi(argv[2]);
40 pthread_t thread[NUM_THREADS];
41 pthread_mutex_t mutex_resource[NUM_THREADS];
43 sem_init(&sem_dining, 0, NUM_THREADS);
45 forks = malloc(NUM_THREADS * sizeof(struct forks));
48 for (i = 0; i < NUM_THREADS; i++) {
49 pthread_mutex_init(&mutex_resource[i], NULL);
50 forks[i] = (struct forks){i,
52 &mutex_resource[(i+1) % NUM_THREADS],
57 for (i = 0; i < NUM_THREADS; i++) {
58 pthread_create(&thread[i], NULL, &philosopher_doit, &forks[i]);
61 for (i = 0; i < NUM_THREADS; i++) {
62 pthread_join(thread[i], NULL);