Lab 10 walkthrough — Dining philosophers using semaphores
Lab 10 walkthrough — Dining philosophers using semaphores
Recorded by Dr. Krithika L.B. Slot lab10-walkthrough
Theory link: 3.5 Classical problems · 3.6 Monitors
Lab 10 walkthrough — Dining philosophers using semaphores
Recorded by Dr. Krithika L.B. Slot lab10-walkthrough
Aim. To implement a deadlock-free solution to the dining-philosophers problem using semaphores.
Each chopstick is a binary semaphore. The naive solution (everyone picks up the left chopstick first) can deadlock. This program uses the
remedy “at most four philosophers may try to eat at once”, implemented with a counting semaphore room = 4:
with four philosophers and five chopsticks, at least one can always get both.
chopstick[5] each = 1 · room = 4.
These programs use POSIX system calls (fork, pthread, shm, semaphore) and must be compiled and run on Linux or WSL — not with Windows MinGW/Turbo C.
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define N 5
sem_t chopstick[N], room;
void *philosopher(void *arg)
{
int i = *(int *)arg;
for (int round = 0; round < 2; round++) {
printf("Philosopher %d is thinking\n", i);
sleep(1);
sem_wait(&room); /* at most 4 at the table */
sem_wait(&chopstick[i]); /* left */
sem_wait(&chopstick[(i + 1) % N]); /* right */
printf("Philosopher %d is eating\n", i);
sleep(1);
sem_post(&chopstick[(i + 1) % N]);
sem_post(&chopstick[i]);
sem_post(&room);
printf("Philosopher %d finished eating\n", i);
}
return NULL;
}
int main(void)
{
pthread_t t[N];
int id[N];
sem_init(&room, 0, N - 1);
for (int i = 0; i < N; i++) sem_init(&chopstick[i], 0, 1);
for (int i = 0; i < N; i++) {
id[i] = i;
pthread_create(&t[i], NULL, philosopher, &id[i]);
}
for (int i = 0; i < N; i++) pthread_join(t[i], NULL);
printf("All philosophers have eaten twice. No deadlock.\n");
return 0;
}gcc dining.c -o dining -pthread./diningroom lines and run many times — occasionally the program hangs with every philosopher holding one chopstick (deadlock). Press Ctrl+C.Philosopher 0 is thinking
Philosopher 1 is thinking
Philosopher 2 is thinking
Philosopher 3 is thinking
Philosopher 4 is thinking
Philosopher 0 is eating
Philosopher 2 is eating
Philosopher 0 finished eating
Philosopher 0 is thinking
Philosopher 2 finished eating
Philosopher 1 is eating
Philosopher 3 is eating
...
All philosophers have eaten twice. No deadlock.Prepare these for the lab evaluation.
Revealed 0All five pick up the left chopstick; each waits for the right one held by a neighbour — circular wait.
Four philosophers share five chopsticks, so at least one has both and can finish.
Not guaranteed — it depends on the fairness of the semaphore queues.
Circular wait.