10 pthread_mutex_t *left_fork;
11 pthread_mutex_t *right_fork;
12 pthread_mutex_t *dining_fork;
15 static void * philosopher_doit(void *forks_arg) {
16 struct forks *forks = forks_arg;
17 pthread_mutex_lock(forks->dining_fork);
18 pthread_mutex_lock(forks->left_fork);
19 pthread_mutex_lock(forks->right_fork);
20 pthread_mutex_unlock(forks->dining_fork);
23 printf("Philosopher %d is eating.\n", forks->philosopher);
25 pthread_mutex_unlock(forks->left_fork);
26 pthread_mutex_unlock(forks->right_fork);
30 int main(int argc, char* argv[])
33 printf("Usage: %s NUM_THREADS DEBUG\n", argv[0]);
37 int NUM_THREADS = atoi(argv[1]);
38 DEBUG = atoi(argv[2]);
40 pthread_t thread[NUM_THREADS];
41 pthread_mutex_t mutex_resource[NUM_THREADS];
42 struct forks forks[NUM_THREADS];
44 pthread_mutex_t dining_fork;
45 pthread_mutex_init(&dining_fork, NULL);
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],
56 for (i = 0; i < NUM_THREADS; i++) {
57 pthread_create(&thread[i], NULL, &philosopher_doit, &forks[i]);
60 for (i = 0; i < NUM_THREADS; i++) {
61 pthread_join(thread[i], NULL);