Welcome to the Dining Philosophers simulation β a classic concurrency problem solved using POSIX threads, mutexes, and optionally processes and semaphores for bonus points.
This project focuses on multithreaded and multiprocess synchronization, avoiding deadlocks, and ensuring thread-safe access to shared resources (forks). Implemented in pure C without any global variables.
philo/
βββ Makefile
βββ philo.h
βββ *.c
philo_bonus/
βββ Makefile
βββ philo_bonus.h
βββ *.c
- Each philosopher is a thread.
- Forks are protected with mutexes to ensure exclusive access.
make -C philo
./philo number_of_philosophers time_to_die time_to_eat time_to_sleep [number_of_times_each_philosopher_must_eat]- Each philosopher is a process.
- Fork access is managed via POSIX semaphores.
make -C philo_bonus
./philo_bonus number_of_philosophers time_to_die time_to_eat time_to_sleep [number_of_times_each_philosopher_must_eat]- Philosophers are seated at a round table with a fork between each pair.
- To eat, a philosopher needs two forks β one on the left and one on the right.
- Philosophers alternate between:
- π§ Thinking
- π Eating
- π΄ Sleeping
- If a philosopher does not eat within
time_to_diemilliseconds, they die. - The simulation ends when:
- A philosopher dies of starvation, or
- (Optional) All philosophers have eaten at least
number_of_times_each_philosopher_must_eattimes.
pthread_createpthread_joinpthread_detachpthread_mutex_initpthread_mutex_destroypthread_mutex_lockpthread_mutex_unlockgettimeofdayusleepwritemallocfreeprintf
Output is timestamped and thread-safe:
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
Xis the philosopher number (starting from 1).timestamp_in_msis the time elapsed since the simulation start in milliseconds.- The message for a philosopher's death must be printed within 10 ms of their actual time of death.
- π§΅ Threads (mandatory): One thread per philosopher, with one mutex per fork.
- π§ͺ Race Conditions: Must be avoided through proper mutex locking.
- π Starvation: Philosophers must not starve (unless it ends the simulation).
- π Thread-Safety: Logs and shared data must be synchronized.
- βοΈ Semaphores (bonus): A single semaphore manages all forks.
- π¦ No global variables allowed.
make/make allβ Compile the program.make cleanβ Remove object (.o) files.make fcleanβ Remove all binaries and object files.make reβ Clean and rebuild the project.
This project is part of the 42 Curriculum and is provided for educational purposes only. Please do not plagiarize.
Built by a 42 student A. Obshatko.