How abdoulkarim22/philosopher works
1. Project type and runtime
- This is a single-process C application built around POSIX threads (pthread) and mutexes.
- It implements the classic Dining Philosophers simulation, so the architecture is centered on concurrent worker threads plus a monitoring path that can stop the simulation safely.
2. Top-level entry point
- src/philo.c is the executable entry point.
- It likely orchestrates the full lifecycle: parse input, initialize shared simulation state, start philosopher threads, run/trigger monitoring, then join and clean up.
3. Core shared model
- philo.h is the central contract for the whole program.
- It likely defines the simulation-wide structure, philosopher structure, mutex layout, and status flags used across actions/, monitor/, threads/, init/, and utils/.
- For an architecture diagram, this header is the “shared domain model” boundary connecting every subsystem.
4. Input parsing and validation boundary
- src/parsing/parse_args.c and src/parsing/validate_args.c handle CLI input.
- They form the first boundary: converting raw argv values into validated numeric simulation parameters such as philosopher count, timing values, and the optional meal target.
- This layer is separate from runtime logic, so invalid configurations are rejected before any threads or mutexes are created.
5. Initialization subsystem
- src/init/init_simulation.c, src/init/init_philosophers.c, and src/init/init_mutexes.c build the runtime state.
- This stage likely allocates philosopher objects, initializes per-philosopher data, sets initial timestamps, and creates the mutexes used for forks and coordination.
- It is the point where static config becomes a live concurrent model.
6. Thread lifecycle management
- src/threads/create_threads.c, src/threads/philosopher_routine.c, and src/threads/join_threads.c manage concurrency.
- Each philosopher is represented by a dedicated thread that repeatedly runs the philosopher routine.
- The thread layer is responsible for starting workers, waiting for them to finish, and coordinating orderly shutdown once the simulation stop condition is reached.
7. Philosopher behavior as actions
- src/actions/eat.c, src/actions/forks.c, src/actions/sleep.c, and src/actions/think.c represent the behavioral phases of a philosopher.
- These are the “business logic” of the simulation: acquire forks, eat, release resources, sleep, and think.
- This layer is where shared-resource contention is handled, making fork mutexes the primary synchronization boundary.
8. Monitoring and stop conditions
- src/monitor/monitor.c, src/monitor/detect_philosopher_death.c, and src/monitor/all_philosophers_ate.c implement supervision.
- The simulation ends when either a philosopher exceeds time_to_die without eating, or when every philosopher has reached the required meal count.
- Architecturally, this is a separate control path from the worker threads: it observes shared state and triggers shutdown without being part of the normal action loop.
9. Time and pacing utilities
- src/time/get_time.c and src/time/precise_sleep.c provide millisecond-level timing.
- Timing is critical because the monitor checks starvation against elapsed time, and the action layer needs accurate sleep durations for simulation behavior.
- This subsystem is the clock source for both state updates and termination checks.
10. Synchronization and output discipline
- src/utils/print_state.c and src/utils/simulation_stop.c are likely the main coordination helpers for output and termination checks.
- In a threaded program, printed state changes usually need serialization to avoid interleaved logs, and stop checks need to be consistent across threads.
- These helpers are part of the shared-control surface rather than the philosopher behavior itself.
11. Cleanup and error handling
- src/utils/cleanup.c and src/utils/error_message.c manage teardown and failure reporting.
- This boundary matters because the program can fail at several stages: parsing, initialization, thread creation, or runtime monitoring.
- Cleanup must handle both successful shutdown and partial initialization failures without leaving mutexes or allocations behind.
12. Data flow summary
- The main flow is: argv → validation → simulation initialization → thread creation → philosopher action loop + monitor loop → stop condition → join/cleanup.
- Shared state moves through the whole program via the structures declared in philo.h, while synchronization is enforced through mutexes around forks, timestamps, and output.
- For an architecture diagram, the key relationships are: parser feeds init, init feeds threads/actions/monitor, and monitor or death detection feeds global stop/cleanup.
13. Build layout
- There is a root Makefile and a src/Makefile, suggesting the project is organized as a compact standalone binary with source files grouped by subsystem.
- The repository is intentionally modular: each directory maps cleanly to a phase of the simulation lifecycle or a concurrency concern.
Main entry points: philo.c Main · init_simulation.c Init sim · philosopher_routine.c Routine · philo.h philo.h
Components 23
Root
Top-level entrypoint and shared contract
Setup
Argument parsing and simulation initialization
- Parse args · Reads raw argv values into simulation parameters
src/parsing/parse_args.c - Validate args · Rejects invalid philosopher counts, timings, and meal limits
src/parsing/validate_args.c - Init sim · Builds the top-level simulation state from validated input
src/init/init_simulation.c - Init philo · Allocates and initializes philosopher records and per-worker state
src/init/init_philosophers.c - Init mutexes · Creates fork and coordination mutexes for shared access
src/init/init_mutexes.c
Runtime
Worker threads, philosopher actions, and monitoring
- Create threads · Spawns philosopher workers for the simulation
src/threads/create_threads.c - Routine · Main per-philosopher loop that repeats the action cycle
src/threads/philosopher_routine.c - Join threads · Waits for workers to finish and drives orderly shutdown
src/threads/join_threads.c - Forks · Handles fork locking and release around eating
src/actions/forks.c - Eat · Performs the eating phase and updates meal timing
src/actions/eat.c - Sleep · Simulates the sleeping phase between meals
src/actions/sleep.c - Think · Simulates the thinking phase before the next cycle
src/actions/think.c - Monitor · Observes shared state and stops the simulation on termination conditions
src/monitor/monitor.c - Detect death · Checks whether any philosopher exceeded time_to_die
src/monitor/detect_philosopher_death.c - All ate · Detects when every philosopher reached the required meal target
src/monitor/all_philosophers_ate.c
Support
Timing, synchronization, and cleanup helpers
- Get time · Returns millisecond timestamps for progress and starvation checks
src/time/get_time.c - Sleep ms · Provides bounded millisecond sleep for simulation pacing
src/time/precise_sleep.c - Print state · Serializes simulation output so thread logs do not interleave
src/utils/print_state.c - Stop flag · Shared stop check used by workers and monitor
src/utils/simulation_stop.c - Cleanup · Destroys mutexes, frees allocations, and handles partial failures
src/utils/cleanup.c - Error msg · Reports parse, init, thread, or runtime failures
src/utils/error_message.c
Connections 34
- Main → Parse args: reads argv · Entry point parses command-line input before any runtime setup
- Parse args → Validate args: validates · Parsed values are checked before the simulation is started
- Validate args → Init sim: accepts · Only valid configuration proceeds to runtime initialization
- Main → Init sim: starts · Main orchestrates simulation setup after input validation
- Init sim → Init philo: builds model · Simulation setup creates philosopher records
- Init sim → Init mutexes: builds sync · Simulation setup creates shared synchronization primitives
- Init sim → Create threads: launches · Initialized state is passed to worker thread creation
- Create threads → Routine: runs · Each created thread executes the philosopher routine
- Routine → Forks: acquires · Routine begins each cycle by taking and releasing forks
- Forks → Eat: enables · Fork ownership allows the eating action to proceed
- Eat → Sleep: next · After eating, the philosopher sleeps
- Sleep → Think: next · Sleeping transitions into thinking
- Think → Routine: loops · Thinking returns the philosopher to the action cycle
- Main → Monitor: supervises · Monitoring runs alongside worker threads to detect stop conditions
- Monitor → Detect death: checks · One termination path is starvation detection
- Monitor → All ate: checks · Another termination path is completion of the meal target
- Detect death → Get time: reads clock · Death detection depends on current timestamps
- All ate → Stop flag: signals stop · Completion detection flips or consults the shared stop state
- Detect death → Stop flag: signals stop · Starvation detection ends the simulation through shared stop state
- Routine → Stop flag: checks · Workers regularly inspect the shared stop flag
- Eat → Get time: timestamps · Eating updates last-meal timing using the clock helper
- Sleep → Sleep ms: paces · Sleeping uses the millisecond sleep helper
- Monitor → Print state: logs · Monitoring path can emit serialized state output
- Routine → Print state: logs · Worker actions are printed through the shared logger
- Main → Join threads: waits · Main waits for worker completion or stop-triggered exit
- Join threads → Cleanup: tears down · After joining, resources are cleaned up
- Main → Cleanup: tears down · Cleanup is used on both success and partial-failure paths
- Main → Error msg: reports · Failures are reported consistently through the error helper
- Cleanup → Stop flag: resets · Teardown depends on shared termination state for safe shutdown
- philo.h → Parse args: defines contract · Parsing uses the shared program contract for configuration fields
- philo.h → Init sim: defines contract · Initialization builds the structs declared in the shared header
- philo.h → Routine: defines contract · Worker logic depends on the shared philosopher and simulation types
- philo.h → Monitor: defines contract · Monitoring reads the same shared state and flags
- philo.h → Cleanup: defines contract · Teardown uses the common ownership and mutex layout