A multithreaded simulation of the classic Dining Philosophers Problem, built in C using POSIX threads and mutexes. This is a 42 school project that explores concurrency, thread synchronization, and resource sharing.
A number of philosophers sit around a circular table. Each philosopher alternates between eating, sleeping, and thinking. There is one fork between each pair of adjacent philosophers, and a philosopher needs two forks to eat. If a philosopher doesn't eat within a given time window, they die.
The challenge is to design a solution where:
- No philosopher starves (unless the timing makes it inevitable).
- No data races occur.
- The simulation stops when a philosopher dies or when all philosophers have eaten the required number of meals.
make # compile
make clean # remove object files
make fclean # remove object files and executable
make re # full recompileThe compiled binary is named philo.
./philo <number_of_philosophers> <time_to_die> <time_to_eat> <time_to_sleep> [number_of_times_each_philosopher_must_eat]
| Argument | Description |
|---|---|
number_of_philosophers |
Number of philosophers (and forks) at the table (max 200) |
time_to_die (ms) |
Time a philosopher can go without eating before dying |
time_to_eat (ms) |
Time it takes for a philosopher to eat |
time_to_sleep (ms) |
Time a philosopher spends sleeping |
number_of_times_each_philosopher_must_eat |
(optional) Simulation stops when every philosopher has eaten at least this many times |
./philo 5 800 200 200 # 5 philosophers, no meal limit
./philo 4 410 200 200 10 # 4 philosophers, each must eat 10 times
./philo 1 800 200 200 # single philosopher (will die)Each state change is logged with a timestamp and philosopher ID:
timestamp_in_ms philosopher_id has taken a fork
timestamp_in_ms philosopher_id is eating
timestamp_in_ms philosopher_id is sleeping
timestamp_in_ms philosopher_id is thinking
timestamp_in_ms philosopher_id died
- Each philosopher runs in its own pthread.
- Forks are protected by mutexes to prevent data races.
- A dedicated monitor thread checks for death and meal completion.
- Timestamps are obtained via
gettimeofday().
| File | Purpose |
|---|---|
main.c |
Entry point and argument validation |
parser.c |
Input parsing and validation |
inits.c |
Initialization of data structures and mutexes |
philosophers.c |
Philosopher routine (eat, sleep, think cycle) |
philos_op.c |
Thread creation, joining, and synchronization helpers |
monitor.c |
Death detection and meal-count monitoring |
utils.c |
Time utilities, custom sleep, and print functions |
strings.c |
String helper functions (ft_atol, ft_strlen, ft_strcmp) |
error.c |
Error and usage message handling |
philo.h |
Header with structs, prototypes, and includes |