Philosophers
C · pthreads
The dining-philosophers concurrency problem, using threads, per-fork mutexes, and a monitor thread.
View on GitHub
A solution to the classic dining-philosophers problem, written in C with POSIX threads. Philosophers sit around a table alternating between eating, sleeping, and thinking. Each needs the two forks next to it to eat, and the simulation has to run without deadlocks and without any philosopher starving.
How it works
- Each philosopher runs in its own thread, and each fork is a mutex, so two neighbours can never hold the same fork at once.
- Forks are always taken in a consistent order, which avoids the circular wait that would otherwise deadlock the table.
- A separate monitor thread watches every philosopher and stops the simulation the moment one goes too long without eating.
- Shared state is guarded by mutexes so the monitor and philosopher threads never race on it.