11 pthread_mutex_t *left_fork;
12 pthread_mutex_t *right_fork;
16 static void * philosopher_doit(void *forks_arg) {
17 struct forks *forks = forks_arg;
18 sem_wait(forks->sem_dining);
19 pthread_mutex_lock(forks->left_fork);
20 pthread_mutex_lock(forks->right_fork);
23 printf("Philosopher %d is eating.\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[])
34 printf("Usage: %s NUM_THREADS DEBUG\n", argv[0]);
38 int NUM_THREADS = atoi(argv[1]);
39 DEBUG = atoi(argv[2]);
41 pthread_t thread[NUM_THREADS];
42 pthread_mutex_t mutex_resource[NUM_THREADS];
43 struct forks forks[NUM_THREADS];
46 sem_init(&sem_dining, 0, NUM_THREADS - 1);
49 for (i = 0; i < NUM_THREADS; i++) {
50 pthread_mutex_init(&mutex_resource[i], NULL);
51 forks[i] = (struct forks){i,
53 &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);