How m-elhouary/philosopher works
Main Components
• CLI & Argument Parser
• Module: parse_arg.c
• Responsibility: validate and convert command-line inputs into a shared configuration structure
• Data Initialization
• Module: initial_data.c
• Responsibility: allocate and initialize shared data (philosopher structs, forks/mutexes, flags)
• Thread Manager
• Module: creat_thread.c
• Responsibility: spawn N philosopher threads + 1 monitor thread
• Philosopher Threads
• Module: simulation.c
• Responsibility: loop through thinking → eating → sleeping
• Monitor Thread
• Module: monitor.c
• Responsibility: periodically check last-meal timestamps, detect death or completion
• Shared Resources & Utilities
• Modules: utils.c, philo_header.h
• Responsibility: timing functions, synchronized printing, mutex definitions, shared flags
Relationships & Data Flows
1. Main (main_philo.c) reads CLI → calls parse_arg → calls initial_data
2. initial_data allocates philosophers[], forks[] (mutex per fork), global print & state mutexes
3. creat_thread spins up:
– N philosopher threads (each receives pointer to its philo struct)
– 1 monitor thread (receives global state pointer)
• Philosopher Lifecycle (concurrent loops)
– Thinking: no locks
– Eating: acquire left-fork mutex → acquire right-fork mutex → update last_meal_time (protected by meal mutex) → sleep for eat_time → release both fork mutexes
– Sleeping: sleep for sleep_time
– Loop until death flag or eat-count reached
• Monitor’s Role
– Polls each philosopher’s last_meal_time under meal mutex
– If any philosopher starves (current_time – last_meal_time > time_to_die), sets end_flag under flag mutex and signals all threads to terminate
– If all meal_counts ≥ required_eats, sets end_flag and signals graceful termination
• Output Synchronization
– All status prints (timestamps, actions) go through a print mutex to avoid interleaving
Architectural Patterns & Design Principles
• Modular C Design: each .c file encapsulates one concern (parsing, init, threading, simulation, monitoring, utils)
• Concurrency via pthreads: one OS thread per philosopher + monitor thread
• Shared-memory synchronization: mutex per fork, one for prints, one for shared-flag/meals
• Deadlock avoidance: enforced fork-acquisition order or asymmetric protocol
– Label every component (Main, Parser, Initializer, Thread Manager, Philosopher Thread, Monitor Thread, Utils)
• Startup control flow →
• Shared-data access ↔
– Annotate critical paths (e.g., fork acquisition order, death detection path)