Created
December 18, 2012 14:22
-
-
Save scvalex/4328392 to your computer and use it in GitHub Desktop.
Starving philosophers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include <stdio.h> | |
void philosopher1(pthread_mutex_t chopsticks[]) { | |
pthread_mutex_lock(&chopsticks[0]); | |
pthread_mutex_lock(&chopsticks[1]); | |
printf("Philosopher 1 is full.\n"); | |
pthread_mutex_unlock(&chopsticks[0]); | |
pthread_mutex_unlock(&chopsticks[1]); | |
} | |
void philosopher2(pthread_mutex_t chopsticks[]) { | |
pthread_mutex_lock(&chopsticks[0]); | |
pthread_mutex_lock(&chopsticks[1]); | |
printf("Philosopher 2 is full.\n"); | |
} | |
int main(int argc, char *argv[]) { | |
pthread_mutex_t chopsticks[2]; | |
pthread_mutex_init(&chopsticks[0], NULL); | |
pthread_mutex_init(&chopsticks[1], NULL); | |
pthread_t threads[2]; | |
pthread_create(&threads[0], NULL, (void* (*)(void*))philosopher2, (void*)chopsticks); | |
pthread_create(&threads[1], NULL, (void* (*)(void*))philosopher1, (void*)chopsticks); | |
pthread_join(threads[0], NULL); | |
pthread_join(threads[1], NULL); | |
pthread_exit(NULL); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment