Skip to content

Instantly share code, notes, and snippets.

@scvalex
Created December 18, 2012 14:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scvalex/4328392 to your computer and use it in GitHub Desktop.
Save scvalex/4328392 to your computer and use it in GitHub Desktop.
Starving philosophers
#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