Dining Philosophers —- Async

查看哲学家进餐以获取问题的描述。

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

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

因为这次您正在使用异步Rust,您将需要一个 tokio 依赖。您可以使用以下的 Cargo.toml

  1. [package]
  2. name = "dining-philosophers-async-dine"
  3. version = "0.1.0"
  4. edition = "2021"
  5. [dependencies]
  6. tokio = { version = "1.26.0", features = ["sync", "time", "macros", "rt-multi-thread"] }

另外,请注意,这次您必须使用来自 tokio 包的 Mutexmpsc 模块。

  • Can you make your implementation single-threaded?