How lauraginer/philosophers works
Project Type and Purpose
• This is a single‐process, multi‐threaded C application that simulates the Dining Philosophers problem.
• Its main goal is to demonstrate thread synchronization, deadlock prevention, precise timing, and safe resource sharing via mutexes.
File Structure Analysis
• Top‐level:
• Makefile – build and debug targets
• inc/philosopher.h – all shared typedefs and function prototypes
• src/ – six modules:
◦ main.c – argument parsing, initialization, thread creation
◦ utils.c – time measurement and conversion utilities
◦ mutex.c – wrapper around pthread_mutex operations
◦ threads.c – philosopher thread routines and teardown
◦ actions.c – philosopher actions (think, eat, sleep)
◦ monitor.c – separate monitor thread for detecting deaths
• Pattern: clear separation of concerns—initialization, utilities, synchronization, threading logic, monitoring.
Key Architectural Components
• Main Controller
• Parses arguments, allocates t_data and philosopher structures, initializes all mutexes and forks array.
• Spawns N philosopher threads + 1 monitor thread.
• Philosopher Threads (N instances)
• Loop: think → pick up forks (mutex lock) → eat → release forks (mutex unlock) → sleep
• Report actions via a thread‐safe logger mutex.
• Monitor Thread
• Periodically scans each philosopher’s last_meal timestamp under eat_mutex.
• If starvation time exceeded, sets a global death flag under dead_mutex and logs death.
• Shared Data (t_data)
• forks: array of N pthread_mutex_t
• dead_mutex, eat_mutex, log_mutex – protect global death flag, meal counters, and console output
• Configuration parameters and initial timestamp
Interactions and Data Flow
• Philosopher threads ↔ forks[] via fork‐mutex locks/unlocks
• Philosopher threads → shared last_meal & meal_count under eat_mutex
• All threads → log output under log_mutex
• Monitor thread reads last_meal & writes death flag under respective mutexes
• Main thread waits for termination and cleans up resources
Architectural Patterns and Principles
• Resource locking via pthread mutexes to avoid race conditions
• Asymmetric fork picking (odd/even ordering) to break circular wait → deadlock prevention
• Busy‐wait sleep (usleep+loop) for sub‐millisecond precision
• Single responsibility modules: easy to locate and extend functionality