Created
March 19, 2017 17:51
-
-
Save porglezomp/eb89ea2d80c0a68426e862ff7c9aa9a6 to your computer and use it in GitHub Desktop.
Socrates and Plato sit down for dinner
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
/* Compile as gcc philosophers.c -pthread */ | |
#include <stdio.h> | |
#include <pthread.h> | |
#include <unistd.h> | |
pthread_mutex_t fork_ = PTHREAD_MUTEX_INITIALIZER; | |
pthread_mutex_t knife = PTHREAD_MUTEX_INITIALIZER; | |
void *socrates(void *nothing) { | |
(void) nothing; | |
/* Comment out the next two lines... */ | |
pthread_mutex_lock(&fork_); | |
printf("Socrates has picked up his fork.\n"); | |
pthread_mutex_lock(&knife); | |
printf("Socrates has picked up his knife.\n"); | |
/* and uncomment these two lines | |
pthread_mutex_lock(&fork_); | |
printf("Socrates has picked up his fork.\n"); | |
*/ | |
printf("Socrates dines.\n"); | |
pthread_mutex_unlock(&fork_); | |
printf("Socrates has set down his fork.\n"); | |
pthread_mutex_unlock(&knife); | |
printf("Socrates has set down his fork.\n"); | |
return NULL; | |
} | |
void *plato(void *nothing) { | |
(void) nothing; | |
pthread_mutex_lock(&fork_); | |
printf("Plato has picked up his fork.\n"); | |
pthread_mutex_lock(&knife); | |
printf("Plato has picked up his knife.\n"); | |
printf("Plato dines.\n"); | |
pthread_mutex_unlock(&fork_); | |
printf("Plato has set down his fork.\n"); | |
pthread_mutex_unlock(&knife); | |
printf("Plato has set down his knife.\n"); | |
return NULL; | |
} | |
int main() { | |
pthread_t a; | |
pthread_t b; | |
pthread_create(&a, NULL, socrates, NULL); | |
pthread_create(&b, NULL, plato, NULL); | |
pthread_join(a, NULL); | |
pthread_join(b, NULL); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment