From d0a1c05d8684e886ddf7fcd7b88c9bc78ecda67c Mon Sep 17 00:00:00 2001 From: Marco Realacci Date: Mon, 17 Mar 2025 10:14:23 +0100 Subject: [PATCH] vault backup: 2025-03-17 10:14:23 --- .obsidian/workspace.json | 4 +- .../notes/4c - Dining Philosophers.md | 43 ++++++++++++++++++- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/.obsidian/workspace.json b/.obsidian/workspace.json index 0cb290e..0ff0932 100644 --- a/.obsidian/workspace.json +++ b/.obsidian/workspace.json @@ -34,9 +34,9 @@ "type": "pdf", "state": { "file": "Concurrent Systems/slides/class 4.pdf", - "page": 18, + "page": 23, "left": -26, - "top": 163, + "top": 359, "zoom": 0.57541567695962 }, "icon": "lucide-file-text", diff --git a/Concurrent Systems/notes/4c - Dining Philosophers.md b/Concurrent Systems/notes/4c - Dining Philosophers.md index c0dac2b..ff2a304 100644 --- a/Concurrent Systems/notes/4c - Dining Philosophers.md +++ b/Concurrent Systems/notes/4c - Dining Philosophers.md @@ -26,4 +26,45 @@ No two neighbors can eat simultaneously, but we can have a deadlock if all philo 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 \ No newline at end of file +So there will be a contention on one fork, so this way a process is automatically excluded. + +``` +semaphores fork[N] all initialized at 1; +Philosopher(i) := + Repeat + think; + if (i < N-1) then + fork[i].down(); + fork[i+1].down(); + else + fork[0].down(); + fork[N-1].down(); + eat; + fork[(i+1)%N].up(); + fork[i].up(); +``` +This is deadlock free. But not much efficient as it may happen that only a philosopher per time will have both the forks (but that is another problem). + +#### Solution 3 +Allow at most N-1 philosophers at a time sitting at the table + +``` +semaphores fork[N] all initialized at 1 +semaphore table initialized at N-1 + +Philosopher(i) := + Repeat + think; + table.down(); + fork[i].down(); + fork[(i+1)%N].down(); + eat; + fork[(i+1)%N].up(); + fork[i].up(); + table.up() +``` +In this case we break the symmetry by letting an odd number of philosophers sit at the table at most. + +#### Solution 4 - Monitors! +Pick up 2 chopsticks only if both are free +a philosopher moves to his/her eating state only if both neighbors are not in their eating states à need to define a state for each philosopher • if one of my neighbors is eating, and I’m hungry, ask them to signal me when they’re done à thus, states of each philosopher are: thinking, hungry, eating à need condition variables to signal waiting hungry philosopher(s) This solutoin very well fits with the features of monitors! \ No newline at end of file