The Philosophers project simulates the classic "Dining Philosophers" problem, where philosophers alternately eat, think, and sleep at a round table with a bowl of spaghetti. Each philosopher needs two forks to eat: one to their left and one to their right. The simulation ensures that philosophers avoid starvation and manage their resources correctly. The goal was to learn the basics of threading a process, create threads and mutexes in C.
To build the project, navigate to the philo
directory and use make
to compile the code. The provided Makefile
will generate the executable named philo
.
make
: Build the project.make all
: Same asmake
.make clean
: Remove object files and temporary files.make fclean
: Remove all files generated bymake
andmake clean
.make re
: Rebuild the project from scratch.
To run the simulation, use the following command:
./philo number_of_philosophers <time_to_die> <time_to_eat> <time_to_sleep> <[number_of_times_each_philosopher_must_eat]>
number_of_philosophers
: The number of philosophers and forks at the table.time_to_die
: The maximum time (in milliseconds) a philosopher can go without eating before dying.time_to_eat
: The time (in milliseconds) it takes for a philosopher to eat.time_to_sleep
: The time (in milliseconds) a philosopher will sleep after eating.number_of_times_each_philosopher_must_eat
(optional): The minimum number of times each philosopher must eat before the simulation stops. If not provided, the simulation stops when a philosopher dies.
./philo 5 800 200 200 3
This command starts a simulation with 5 philosophers, where each philosopher will die if they don't eat within 800 milliseconds. Eating takes 200 milliseconds, and sleeping takes 200 milliseconds. Each philosopher must eat at least 3 times for the simulation to stop.
The program logs the state changes of each philosopher. The logs are formatted as follows:
timestamp_in_ms X has taken a fork
timestamp_in_ms X is eating
timestamp_in_ms X is sleeping
timestamp_in_ms X is thinking
timestamp_in_ms X died
- Each philosopher is represented as a thread.
- There is a mutex for each fork to prevent race conditions.
- Philosophers take their left and right forks to eat and release them after eating.
- The simulation will handle synchronization to ensure philosophers avoid deadlock and starvation.