29 lines
No EOL
1.2 KiB
Markdown
29 lines
No EOL
1.2 KiB
Markdown
The first real practical example of a concurrent system.
|
|
- $N$ philosophers seated around a circular table
|
|
- one chopstick between each pair of philosophers
|
|
- a philosophers must pick up its two nearest chopsticks in order to eat
|
|
- a philosopher must pick up first one chopstick, then the second one, not both at once
|
|
![[Pasted image 20250317100456.png|100]]
|
|
|
|
**PROBLEM:** *Devise a deadlock-free algorithm for allocating these limited resources (chopsticks) among several processes (philosophers).*
|
|
|
|
#### A wrong solution
|
|
each chopstick is governed by a mutual exclusion semaphore that prevents any other philosopher from picking up the chopstick when it is already in use by another philosopher
|
|
|
|
```
|
|
semaphore chopstick[5] initialized to 1
|
|
Philosopher(i) :=
|
|
while(1) do
|
|
chopstick[i].down()
|
|
chopstick[(i+1)%N].down()
|
|
// eat
|
|
chopstick[(i+1)%N].up()
|
|
chopstick[i].up()
|
|
```
|
|
No two neighbors can eat simultaneously, but we can have a deadlock if all philosophers grab their right chopstick simultaneously.
|
|
|
|
#### Solution 1
|
|
Give a number to all forks and always try with the smaller.
|
|
All philosophers must first pick left and then right, except for the last one that first picks right and then left.
|
|
|
|
So there will be c |