5.4.concurrency-semaphore
5.4.concurrency-semaphore
Endadul Hoque
Acknowledgement
(Cont.)
16 void *consumer(void *arg) {
17 int i;
18 for (i = 0; i < loops; i++) {
19 sem_wait(&mutex); // line c0 (NEW LINE)
20 sem_wait(&full); // line c1
21 int tmp = get(); // line c2
22 sem_post(&empty); // line c3
23 sem_post(&mutex); // line c4 (NEW LINE)
24 printf("%d\n", tmp);
25 }
26 }
f3 f0
P3 P4
f4
The Dining Philosophers
• Key challenges
– There is no deadlock.
– No philosopher starves and never gets to eat.
– Concurrency is high.
• Deadlock occurs!
– If each philosopher happens to grab the fork on their left before
any philosopher can grab the fork on their right.
– Each will be stuck holding one fork and waiting for another, forever.
A Solution: Breaking The Dependency
• Change how forks are acquired.
– Let’s assume that philosopher 4 acquire the forks in a
different order.
1 void getforks() {
2 if (p == 4) {
3 sem_wait(forks[right(p)]);
4 sem_wait(forks[left(p)]);
5 } else {
6 sem_wait(forks[left(p)]);
7 sem_wait(forks[right(p)]);
8 }
9 }