C · threads · mutexes · semaphores · 42 Common Core
Philosophers
The dining philosophers problem in C: threads that share forks, eat on time and never deadlock.
The problem
The problem
Philosophers sit around a table with one fork between each pair and need two to eat. Keep every one of them alive within a time limit, without deadlocks or data races, and report a death within a few milliseconds.
What I built
- A version with one thread per philosopher and one mutex per fork.
- A bonus version with one process per philosopher and the forks as a counting semaphore.
- Argument parsing, an optional meal count, and a monitor that stops the simulation on the first death.
Technical decisions
- Atomics for the meal count and last-meal time, so the monitor can read them without taking a lock.
- One lock around printing, so status lines never interleave and nothing prints after a death.
- A custom sleep that checks the stop flag, instead of one long usleep that oversleeps.
What makes it hard
- Deadlock: if everyone picks up the same fork first, nobody eats.
- Timing: a few milliseconds of drift decides whether a philosopher lives or dies.
What I can do because of it
- Write concurrent code with threads, mutexes and semaphores, and spot race conditions.
- Choose between threads and processes for a job and clean up both properly.