Skip to content

ahokcool/philosophers

Repository files navigation


ahokcool
An overview of all my projects can be found here: ahokcool

42
This project was created as part of my studies at: 42 Lisboa


Logo

philosophers

program that simulates the life of a group of philosophers to learn the basics of threading a process an mutexes.


💡 Lessons learned

  • multithreading in C
  • race condition
  • C mutex lock
  • deadlocks

Installation

$ git clone https://github.com/ahokcool/philosophers.git  # Clone
$ cd philosophers                                         # Change directory
$ make                                                    # Compile
$ ./philo 800 200 200 7                                   # Run

More Information

This project is a version of the dinning philosopher problem
->Wikipedia

Common Problems My Solution
independent philos -> using threads
race conditions -> using pthread_mutex
deadlocks -> resource hierarchy solution
the starvation -> wait for a lap time

The starvation solution

Every philo can see how many other philos are sitting at the table. Always half of the philos (result rounded down) can eat at the same time (exception: there is only one philo). Since in this variant all philos always eat the same amount of time, it can be calculated how long it takes until all have started to eat once. If each philo now waits until at least this time has passed before he eats again, nobody starves anymore. HOORAY!

Formula
table->min_wait_time = ((table->num_philos - (int)(table->num_philos / 2) - 1) * table->dur_eat) + (table->dur_eat * 0.5)

Note:
I noticed that this wastes 0.5*dur_eat ms per food round. So a philo could eat, but he does not. So, since I did not come up with a solution, I simply adjusted the formula and waste now only 5ms. (which is still not ideal)
New formula
table->min_wait_time = ((table->num_philos - (int)(table->num_philos / 2) - 1) * table->dur_eat) + 5;


🔝 back to top 🔝

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published