How iantar1/philosophers works
Project type and purpose
• This is a C-based concurrency demo implementing the Dining Philosophers problem in two flavours:
a) “philo” uses POSIX mutexes
b) “philo_bonus” uses POSIX semaphores
• Its goal is to illustrate thread creation, shared-resource synchronization, race-condition avoidance, and graceful shutdown.
File structure
• Top-level:
• README.md – project description and theory
• subject.pdf – problem statement
• philo/ – mutex-based implementation
• philo_bonus/ – semaphore-based implementation
• philo/ and philo_bonus/ are nearly parallel in structure:
• Makefile – compile rules with gcc and -pthread or –lrt
• *.c – core modules (parsing, philosopher routines, utilities)
• *.h – shared data structures (t_philosopher, t_args)
• Key modules in each:
• parce*.c – command-line argument parsing
• philosophers*.c – thread entry point and lifecycle (think, eat, sleep loops)
• utils*.c – time tracking, printing wrappers (ft_printf), cleanup
• bonus version adds utils3.c for semaphore helpers
Extract additional insights from the README
• Emphasis on:
• What a thread is, vs a process
• Race conditions
• Semaphores for mutual exclusion
Main components
a. Configuration & Parser
• reads N philosophers, time_to_die, time_to_eat, time_to_sleep, optional meals limit
• outputs a shared args struct
b. Main/Controller
• initializes synchronization primitives (mutex array or semaphores)
• spawns N philosopher threads
• joins threads and cleans up resources
c. Philosopher Threads (N instances)
• Each thread runs:
1) attempt to acquire left & right forks (mutex_lock or sem_wait)
2) record last_meal_time, ft_printf(“is eating”)
3) release forks (mutex_unlock or sem_post)
4) ft_printf(“is sleeping”), usleep
5) ft_printf(“is thinking”)
6) loop until death or meal count reached
d. Fork Resources
• philo: array of N pthread_mutex_t
• philo_bonus: two semaphores (“forks” count = N, “write” = 1)
e. Logger (/ft_printf)
• single synchronized output stream to avoid interleaved prints
Relationships and interactions
• Main → Parser: read CLI args
• Main → Sync Primitives: initialize mutexes/semaphores
• Main → Philosopher Threads: pthread_create / fork N threads
• Philosopher Threads ↔ Fork Resources: lock/unlock or sem_wait/sem_post
• Philosopher Threads → Logger: ft_printf with a write semaphore/mutex
• Main ← Philosopher Threads: pthread_join, check for termination
Architectural patterns & design principles
• Shared-resource synchronization (mutex or semaphore)
• Worker threads pattern with centralized resource manager
• Separation of concerns: parsing, core logic, utilities, I/O
Relevant technologies
• Language: C
• Build: Makefile, GCC
• Concurrency: pthreads, POSIX mutex, POSIX semaphores
• Utility: custom ft_printf for thread-safe logging
Detail
• Lifecycle loop of each philosopher with states (Think → Eat → Sleep)
• Shared argument struct as a singleton data store
• Termination/cleanup path back to Controller