#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
sem_t room;
sem_t chopstick[5];
void eat(int phil);
void* philosopher(void* num) {
int phil = *(int*)num;
sem_wait(&room);
printf("\nPhilosopher %d is thinking", phil
); sleep(1);
sem_wait(&chopstick[phil]);
sem_wait(&chopstick[(phil+1)%5]);
eat(phil);
sleep(1);
sem_post(&chopstick[phil]);
sem_post(&chopstick[(phil+1)%5]);
printf("\nPhilosopher %d finished eating", phil
);
sem_post(&room);
return NULL;
}
void eat(int phil) {
printf("\nPhilosopher %d is eating", phil
); }
int main() {
int i, a[5];
pthread_t tid[5];
sem_init(&room, 0, 4);
for (i = 0; i < 5; i++) {
sem_init(&chopstick[i], 0, 1);
}
for (i = 0; i < 5; i++) {
a[i] = i;
pthread_create(&tid[i], NULL, philosopher, (void*) &a[i]);
}
for (i = 0; i < 5; i++) {
pthread_join(tid[i], NULL);
}
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KI2luY2x1ZGUgPHB0aHJlYWQuaD4KI2luY2x1ZGUgPHNlbWFwaG9yZS5oPgojaW5jbHVkZSA8dW5pc3RkLmg+CgpzZW1fdCByb29tOwpzZW1fdCBjaG9wc3RpY2tbNV07Cgp2b2lkIGVhdChpbnQgcGhpbCk7Cgp2b2lkKiBwaGlsb3NvcGhlcih2b2lkKiBudW0pIHsKICAgIGludCBwaGlsID0gKihpbnQqKW51bTsKCiAgICBzZW1fd2FpdCgmcm9vbSk7CgogICAgcHJpbnRmKCJcblBoaWxvc29waGVyICVkIGlzIHRoaW5raW5nIiwgcGhpbCk7CiAgICBzbGVlcCgxKTsKCiAgICBzZW1fd2FpdCgmY2hvcHN0aWNrW3BoaWxdKTsKICAgIHNlbV93YWl0KCZjaG9wc3RpY2tbKHBoaWwrMSklNV0pOwoKICAgIGVhdChwaGlsKTsKCiAgICBzbGVlcCgxKTsKCiAgICBzZW1fcG9zdCgmY2h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