Fixed issues with semaphores. Program fully functional

This commit is contained in:
TriantaTV 2022-10-03 03:31:33 -05:00
parent 431dcb6aa6
commit c31b3b632c
2 changed files with 6 additions and 4 deletions

View File

@ -86,15 +86,15 @@ void* Philosopher(void* philosopherPassed)
PhilosopherData *philosopherSelected = (PhilosopherData*) philosopherPassed; PhilosopherData *philosopherSelected = (PhilosopherData*) philosopherPassed;
while (true) while (true)
{ {
Think(philosopherSelected); /*philosopher is thinking*/ if (philosopherSelected->eatingCount > 2)
if (philosopherSelected->eatingCount == 2)
{ {
printf("Philosopher %d ate twice...\n", philosopherSelected->position); // printf("Philosopher %d ate twice...\n", philosopherSelected->position);
return; return;
} }
TakeForks(philosopherSelected); /*acquire two forks or block*/ TakeForks(philosopherSelected); /*acquire two forks or block*/
Eat(philosopherSelected); /*yum-yum, spaghetti*/ Eat(philosopherSelected); /*yum-yum, spaghetti*/
PutForks(philosopherSelected); /*put both forks back on table*/ PutForks(philosopherSelected); /*put both forks back on table*/
Think(philosopherSelected); /*philosopher is thinking*/
} }
} }
@ -106,9 +106,10 @@ void PhilosopherInit(int philosopherTotal)
sem_init(&semaphore, 0, 1); sem_init(&semaphore, 0, 1);
while (!AllPhilosophersFull(PhilosopherList, philosopherTotal)) while (!AllPhilosophersFull(PhilosopherList, philosopherTotal))
{ {
AllowPhilosopher();
sleep(1); sleep(1);
AllowPhilosopher();
} }
sleep(5);
for (int i = 0; i < philosopherTotal; i++) for (int i = 0; i < philosopherTotal; i++)
{ {
printf("Philosopher %d eating count: %d\n", PhilosopherList[i].position, PhilosopherList[i].eatingCount); printf("Philosopher %d eating count: %d\n", PhilosopherList[i].position, PhilosopherList[i].eatingCount);
@ -123,6 +124,7 @@ void PhilosopherListInit(PhilosopherData PhilosopherList[], int philosopherTotal
PhilosopherList[i].position = i; PhilosopherList[i].position = i;
PhilosopherList[i].eatingCount = 0; PhilosopherList[i].eatingCount = 0;
PhilosopherList[i].state = THINKING; PhilosopherList[i].state = THINKING;
printf("Philosopher %d is thinking...\n", i);
pthread_create(&PhilosopherList[i].thread, NULL, &Philosopher, &PhilosopherList[i]); pthread_create(&PhilosopherList[i].thread, NULL, &Philosopher, &PhilosopherList[i]);
} }
} }

Binary file not shown.