Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 

Repository files navigation

This project has been created as part of the 42 curriculum by mkugan.

Philosophers

I never thought philosophy would be so deadly

An implementation of the Dining Philosophers problem — a classic concurrency challenge by Edsger Dijkstra. The project comes in two parts: a mandatory version using threads and mutexes, and a bonus version using processes and semaphores.

Description

One or more philosophers sit around a round table with a large bowl of spaghetti. There are as many forks as philosophers, one between each pair of neighbors. A philosopher must pick up both their left and right fork to eat — and can only hold one fork at a time. After eating they sleep, then think, then try to eat again. If a philosopher goes too long without eating, they die. The goal is to keep everyone alive.

Mandatory part (philo/) — each philosopher is a thread; forks are protected with mutexes.

Bonus part (philo_bonus/) — each philosopher is a child process; the pool of forks is managed with a semaphore.

State log format

Every state change is printed to stdout:

timestamp_in_ms  N  has taken a fork
timestamp_in_ms  N  is eating
timestamp_in_ms  N  is sleeping
timestamp_in_ms  N  is thinking
timestamp_in_ms  N  died

Where timestamp_in_ms is elapsed time since the simulation started and N is the philosopher number (1-indexed). Messages never overlap; a death message appears within 10 ms of the actual death.

Instructions

Requirements

  • C compiler (cc) with support for POSIX threads
  • make
  • macOS or Linux

Build

# Mandatory part
cd philo
make

# Bonus part
cd philo_bonus
make

Both Makefiles support the standard rules: all, clean, fclean, re.

Usage

./philo number_of_philosophers time_to_die time_to_eat time_to_sleep [number_of_times_each_philosopher_must_eat]
Argument Unit Description
number_of_philosophers Number of philosophers (and forks)
time_to_die ms A philosopher dies if they haven't started eating within this time since their last meal (or the simulation start)
time_to_eat ms How long eating takes (holds two forks)
time_to_sleep ms How long sleeping takes
number_of_times_each_philosopher_must_eat Optional. Simulation ends when all philosophers have eaten at least this many times

Examples

# 5 philosophers, none should die
./philo 5 800 200 200

# 4 philosophers, each must eat 7 times
./philo 4 410 200 200 7

# 1 philosopher — will always die (only one fork)
./philo 1 800 200 200

Resources

AI usage

AI was used to draft this README based on the project subject requirements.

About

Dining philosophers problem in C — threads & mutexes (mandatory) · processes & semaphores (bonus)

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Contributors

Languages