Created
January 15, 2017 10:03
-
-
Save sagarpanchal/03d7cb8fdd3f89783701dde2e0835b43 to your computer and use it in GitHub Desktop.
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 <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <semaphore.h> | |
#include <pthread.h> | |
#define N 5 | |
#define THINKING 0 | |
#define HUNGRY 1 | |
#define EATING 2 | |
#define LEFT (ph_num + 4) % N | |
#define RIGHT (ph_num + 1) % N | |
sem_t mutex; | |
sem_t S[N]; | |
void * phil(void *num); | |
void fork_pick(int); | |
void fork_put(int); | |
void check(int); | |
int state[N]; | |
int phil_num[N] = { 0, 1, 2, 3, 4 }; | |
int main() | |
{ | |
int i; | |
pthread_t thread_id[N]; | |
sem_init(&mutex, 0, 1); | |
system("tput reset"); | |
for (i = 0; i < N; i++) sem_init(&S[i], 0, 0); | |
printf("Init\n"); | |
for (i = 0; i < N; i++) { | |
printf("P%d - Thinking\n", i+1); | |
pthread_create(&thread_id[i], NULL, phil, &phil_num[i]); | |
} | |
printf("-----\n"); | |
for (i = 0; i < N; i++) pthread_join(thread_id[i], NULL); | |
} | |
void *phil(void *num) | |
{ | |
int n = 1; | |
while(n < 2) { | |
int *i = num; | |
sleep(1); | |
fork_pick(*i); | |
sleep(0); | |
fork_put(*i); | |
n++; // Uncomment to stop infinite loop | |
} | |
} | |
void fork_pick(int ph_num) | |
{ | |
sem_wait(&mutex); | |
state[ph_num] = HUNGRY; | |
printf("P%d - Hungry\n-----\n", ph_num + 1); | |
check(ph_num); | |
sem_post(&mutex); | |
sem_wait(&S[ph_num]); | |
sleep(1); | |
} | |
void check(int ph_num) | |
{ | |
if (state[ph_num] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) { | |
state[ph_num] = EATING; | |
sleep(2); | |
printf("P%d - Picks forks %d and %d\n", ph_num + 1, LEFT + 1, ph_num + 1); | |
printf("P%d - Eating\n-----\n", ph_num + 1); | |
sem_post(&S[ph_num]); | |
} | |
} | |
void fork_put(int ph_num) | |
{ | |
sem_wait(&mutex); | |
state[ph_num] = THINKING; | |
printf("P%d - Releases forks %d and %d\n", ph_num + 1, LEFT + 1, ph_num + 1); | |
printf("P%d - Thinking\n-----\n", ph_num + 1); | |
check(LEFT); | |
check(RIGHT); | |
sem_post(&mutex); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment