Dining Philosophers

The dining philosophers problem is a classic problem in concurrency:

Five philosophers dine together at the same table. Each philosopher has their own place at the table. There is a fork between each plate. The dish served is a kind of spaghetti which has to be eaten with two forks. Each philosopher can only alternately think and eat. Moreover, a philosopher can only eat their spaghetti when they have both a left and right fork. Thus two forks will only be available when their two nearest neighbors are thinking, not eating. After an individual philosopher finishes eating, they will put down both forks.

You will need a local Cargo installation for this exercise. Copy the code below to src/main.rs file, fill out the blanks, and test that cargo run does not deadlock:

  1. use std::sync::mpsc;
  2. use std::sync::{Arc, Mutex};
  3. use std::thread;
  4. use std::time::Duration;
  5. struct Fork;
  6. struct Philosopher {
  7. name: String,
  8. // left_fork: ...
  9. // right_fork: ...
  10. // thoughts: ...
  11. }
  12. impl Philosopher {
  13. fn think(&self) {
  14. self.thoughts
  15. .send(format!("Eureka! {} has a new idea!", &self.name))
  16. .unwrap();
  17. }
  18. fn eat(&self) {
  19. // Pick up forks...
  20. println!("{} is eating...", &self.name);
  21. thread::sleep(Duration::from_millis(10));
  22. }
  23. }
  24. static PHILOSOPHERS: &[&str] =
  25. &["Socrates", "Plato", "Aristotle", "Thales", "Pythagoras"];
  26. fn main() {
  27. // Create forks
  28. // Create philosophers
  29. // Make them think and eat
  30. // Output their thoughts
  31. }