# abdoulkarim22/philosopher architecture

> Architecture diagram of the GitHub repository abdoulkarim22/philosopher, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-02). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/abdoulkarim22/philosopher
- Repository: https://github.com/abdoulkarim22/philosopher

## Overview

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: [`src/philo.c`](https://github.com/abdoulkarim22/philosopher/blob/master/src/philo.c) (Main), [`src/init/init_simulation.c`](https://github.com/abdoulkarim22/philosopher/blob/master/src/init/init_simulation.c) (Init sim), [`src/threads/philosopher_routine.c`](https://github.com/abdoulkarim22/philosopher/blob/master/src/threads/philosopher_routine.c) (Routine), [`philo.h`](https://github.com/abdoulkarim22/philosopher/blob/master/philo.h) (philo.h)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_root["Root"]
  node_philo_h["philo.h<br/>shared model<br/>[philo.h]"]
  node_main["Main<br/>entrypoint<br/>[philo.c]"]
end

subgraph group_setup["Setup"]
  node_parse_args["Parse args<br/>cli parsing<br/>[parse_args.c]"]
  node_validate_args["Validate args<br/>input check<br/>[validate_args.c]"]
  node_init_simulation["Init sim<br/>runtime setup<br/>[init_simulation.c]"]
  node_init_philosophers["Init philo<br/>model setup"]
  node_init_mutexes["Init mutexes<br/>sync setup<br/>[init_mutexes.c]"]
end

subgraph group_runtime["Runtime"]
  node_create_threads["Create threads<br/>thread start<br/>[create_threads.c]"]
  node_philo_routine(("Routine<br/>worker loop"))
  node_join_threads["Join threads<br/>thread join<br/>[join_threads.c]"]
  node_forks{{"Forks<br/>resource acquire<br/>[forks.c]"}}
  node_eat(("Eat<br/>action<br/>[eat.c]"))
  node_sleep(("Sleep<br/>action<br/>[sleep.c]"))
  node_think(("Think<br/>action<br/>[think.c]"))
  node_monitor["Monitor<br/>supervisor<br/>[monitor.c]"]
  node_detect_death(("Detect death<br/>watchdog"))
  node_all_ate(("All ate<br/>completion check"))
end

subgraph group_support["Support"]
  node_get_time(("Get time<br/>clock<br/>[get_time.c]"))
  node_precise_sleep(("Sleep ms<br/>timing<br/>[precise_sleep.c]"))
  node_print_state["Print state<br/>logging<br/>[print_state.c]"]
  node_simulation_stop{{"Stop flag<br/>control<br/>[simulation_stop.c]"}}
  node_cleanup["Cleanup<br/>teardown<br/>[cleanup.c]"]
  node_error_message["Error msg<br/>diagnostics<br/>[error_message.c]"]
end

node_main -->|"reads argv"| node_parse_args
node_parse_args -->|"validates"| node_validate_args
node_validate_args -->|"accepts"| node_init_simulation
node_main -->|"starts"| node_init_simulation
node_init_simulation -->|"builds model"| node_init_philosophers
node_init_simulation -->|"builds sync"| node_init_mutexes
node_init_simulation -->|"launches"| node_create_threads
node_create_threads -->|"runs"| node_philo_routine
node_philo_routine -->|"acquires"| node_forks
node_forks -->|"enables"| node_eat
node_eat -->|"next"| node_sleep
node_sleep -->|"next"| node_think
node_think -->|"loops"| node_philo_routine
node_main -->|"supervises"| node_monitor
node_monitor -->|"checks"| node_detect_death
node_monitor -->|"checks"| node_all_ate
node_detect_death -->|"reads clock"| node_get_time
node_all_ate -->|"signals stop"| node_simulation_stop
node_detect_death -->|"signals stop"| node_simulation_stop
node_philo_routine -->|"checks"| node_simulation_stop
node_eat -->|"timestamps"| node_get_time
node_sleep -->|"paces"| node_precise_sleep
node_monitor -->|"logs"| node_print_state
node_philo_routine -->|"logs"| node_print_state
node_main -->|"waits"| node_join_threads
node_join_threads -->|"tears down"| node_cleanup
node_main -->|"tears down"| node_cleanup
node_main -->|"reports"| node_error_message
node_cleanup -->|"resets"| node_simulation_stop
node_philo_h -.->|"defines contract"| node_parse_args
node_philo_h -.->|"defines contract"| node_init_simulation
node_philo_h -.->|"defines contract"| node_philo_routine
node_philo_h -.->|"defines contract"| node_monitor
node_philo_h -.->|"defines contract"| node_cleanup

click node_philo_h "https://github.com/abdoulkarim22/philosopher/blob/master/philo.h"
click node_main "https://github.com/abdoulkarim22/philosopher/blob/master/src/philo.c"
click node_parse_args "https://github.com/abdoulkarim22/philosopher/blob/master/src/parsing/parse_args.c"
click node_validate_args "https://github.com/abdoulkarim22/philosopher/blob/master/src/parsing/validate_args.c"
click node_init_simulation "https://github.com/abdoulkarim22/philosopher/blob/master/src/init/init_simulation.c"
click node_init_philosophers "https://github.com/abdoulkarim22/philosopher/blob/master/src/init/init_philosophers.c"
click node_init_mutexes "https://github.com/abdoulkarim22/philosopher/blob/master/src/init/init_mutexes.c"
click node_create_threads "https://github.com/abdoulkarim22/philosopher/blob/master/src/threads/create_threads.c"
click node_philo_routine "https://github.com/abdoulkarim22/philosopher/blob/master/src/threads/philosopher_routine.c"
click node_join_threads "https://github.com/abdoulkarim22/philosopher/blob/master/src/threads/join_threads.c"
click node_forks "https://github.com/abdoulkarim22/philosopher/blob/master/src/actions/forks.c"
click node_eat "https://github.com/abdoulkarim22/philosopher/blob/master/src/actions/eat.c"
click node_sleep "https://github.com/abdoulkarim22/philosopher/blob/master/src/actions/sleep.c"
click node_think "https://github.com/abdoulkarim22/philosopher/blob/master/src/actions/think.c"
click node_monitor "https://github.com/abdoulkarim22/philosopher/blob/master/src/monitor/monitor.c"
click node_detect_death "https://github.com/abdoulkarim22/philosopher/blob/master/src/monitor/detect_philosopher_death.c"
click node_all_ate "https://github.com/abdoulkarim22/philosopher/blob/master/src/monitor/all_philosophers_ate.c"
click node_get_time "https://github.com/abdoulkarim22/philosopher/blob/master/src/time/get_time.c"
click node_precise_sleep "https://github.com/abdoulkarim22/philosopher/blob/master/src/time/precise_sleep.c"
click node_print_state "https://github.com/abdoulkarim22/philosopher/blob/master/src/utils/print_state.c"
click node_simulation_stop "https://github.com/abdoulkarim22/philosopher/blob/master/src/utils/simulation_stop.c"
click node_cleanup "https://github.com/abdoulkarim22/philosopher/blob/master/src/utils/cleanup.c"
click node_error_message "https://github.com/abdoulkarim22/philosopher/blob/master/src/utils/error_message.c"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_philo_h,node_main toneBlue
class node_parse_args,node_validate_args,node_init_simulation,node_init_philosophers,node_init_mutexes toneAmber
class node_create_threads,node_philo_routine,node_join_threads,node_forks,node_eat,node_sleep,node_think,node_monitor,node_detect_death,node_all_ate toneMint
class node_get_time,node_precise_sleep,node_print_state,node_simulation_stop,node_cleanup,node_error_message toneRose
```

## Components

### Root

Top-level entrypoint and shared contract

- [philo.h](https://github.com/abdoulkarim22/philosopher/blob/master/philo.h): shared model · Central simulation structures, state flags, and mutex contracts used across the program · `philo.h`
- [Main](https://github.com/abdoulkarim22/philosopher/blob/master/src/philo.c): entrypoint · Program lifecycle orchestration from startup to shutdown · `src/philo.c`

### Setup

Argument parsing and simulation initialization

- [Parse args](https://github.com/abdoulkarim22/philosopher/blob/master/src/parsing/parse_args.c): cli parsing · Reads raw argv values into simulation parameters · `src/parsing/parse_args.c`
- [Validate args](https://github.com/abdoulkarim22/philosopher/blob/master/src/parsing/validate_args.c): input check · Rejects invalid philosopher counts, timings, and meal limits · `src/parsing/validate_args.c`
- [Init sim](https://github.com/abdoulkarim22/philosopher/blob/master/src/init/init_simulation.c): runtime setup · Builds the top-level simulation state from validated input · `src/init/init_simulation.c`
- [Init philo](https://github.com/abdoulkarim22/philosopher/blob/master/src/init/init_philosophers.c): model setup · Allocates and initializes philosopher records and per-worker state · `src/init/init_philosophers.c`
- [Init mutexes](https://github.com/abdoulkarim22/philosopher/blob/master/src/init/init_mutexes.c): sync setup · Creates fork and coordination mutexes for shared access · `src/init/init_mutexes.c`

### Runtime

Worker threads, philosopher actions, and monitoring

- [Create threads](https://github.com/abdoulkarim22/philosopher/blob/master/src/threads/create_threads.c): thread start · Spawns philosopher workers for the simulation · `src/threads/create_threads.c`
- [Routine](https://github.com/abdoulkarim22/philosopher/blob/master/src/threads/philosopher_routine.c): worker loop · Main per-philosopher loop that repeats the action cycle · `src/threads/philosopher_routine.c`
- [Join threads](https://github.com/abdoulkarim22/philosopher/blob/master/src/threads/join_threads.c): thread join · Waits for workers to finish and drives orderly shutdown · `src/threads/join_threads.c`
- [Forks](https://github.com/abdoulkarim22/philosopher/blob/master/src/actions/forks.c): resource acquire · Handles fork locking and release around eating · `src/actions/forks.c`
- [Eat](https://github.com/abdoulkarim22/philosopher/blob/master/src/actions/eat.c): action · Performs the eating phase and updates meal timing · `src/actions/eat.c`
- [Sleep](https://github.com/abdoulkarim22/philosopher/blob/master/src/actions/sleep.c): action · Simulates the sleeping phase between meals · `src/actions/sleep.c`
- [Think](https://github.com/abdoulkarim22/philosopher/blob/master/src/actions/think.c): action · Simulates the thinking phase before the next cycle · `src/actions/think.c`
- [Monitor](https://github.com/abdoulkarim22/philosopher/blob/master/src/monitor/monitor.c): supervisor · Observes shared state and stops the simulation on termination conditions · `src/monitor/monitor.c`
- [Detect death](https://github.com/abdoulkarim22/philosopher/blob/master/src/monitor/detect_philosopher_death.c): watchdog · Checks whether any philosopher exceeded time_to_die · `src/monitor/detect_philosopher_death.c`
- [All ate](https://github.com/abdoulkarim22/philosopher/blob/master/src/monitor/all_philosophers_ate.c): completion check · Detects when every philosopher reached the required meal target · `src/monitor/all_philosophers_ate.c`

### Support

Timing, synchronization, and cleanup helpers

- [Get time](https://github.com/abdoulkarim22/philosopher/blob/master/src/time/get_time.c): clock · Returns millisecond timestamps for progress and starvation checks · `src/time/get_time.c`
- [Sleep ms](https://github.com/abdoulkarim22/philosopher/blob/master/src/time/precise_sleep.c): timing · Provides bounded millisecond sleep for simulation pacing · `src/time/precise_sleep.c`
- [Print state](https://github.com/abdoulkarim22/philosopher/blob/master/src/utils/print_state.c): logging · Serializes simulation output so thread logs do not interleave · `src/utils/print_state.c`
- [Stop flag](https://github.com/abdoulkarim22/philosopher/blob/master/src/utils/simulation_stop.c): control · Shared stop check used by workers and monitor · `src/utils/simulation_stop.c`
- [Cleanup](https://github.com/abdoulkarim22/philosopher/blob/master/src/utils/cleanup.c): teardown · Destroys mutexes, frees allocations, and handles partial failures · `src/utils/cleanup.c`
- [Error msg](https://github.com/abdoulkarim22/philosopher/blob/master/src/utils/error_message.c): diagnostics · Reports parse, init, thread, or runtime failures · `src/utils/error_message.c`

## Connections

- 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
