哲學家就餐問題 — 非同步
請參閱哲學家就餐問題,查看題目說明。
和之前一樣,這項練習需要在本機安裝 Cargo。請將以下程式碼複製到名為 src/main.rs
的檔案、填寫空白處,然後測試 cargo run
不會發生死結:
use std::sync::Arc;
use tokio::sync::mpsc::{self, Sender};
use tokio::sync::Mutex;
use tokio::time;
struct Fork;
struct Philosopher {
name: String,
// left_fork: ...
// right_fork: ...
// thoughts: ...
}
impl Philosopher {
async fn think(&self) {
self.thoughts
.send(format!("Eureka! {} has a new idea!", &self.name))
.await
.unwrap();
}
async fn eat(&self) {
// Keep trying until we have both forks
println!("{} is eating...", &self.name);
time::sleep(time::Duration::from_millis(5)).await;
}
}
static PHILOSOPHERS: &[&str] =
&["Socrates", "Hypatia", "Plato", "Aristotle", "Pythagoras"];
#[tokio::main]
async fn main() {
// Create forks
// Create philosophers
// Make them think and eat
// Output their thoughts
}
這次是使用非同步 Rust,因此會需要 tokio
依附元件。您可以使用下列 Cargo.toml
:
[package]
name = "dining-philosophers-async-dine"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = { version = "1.26.0", features = ["sync", "time", "macros", "rt-multi-thread"] }
另請注意,這次必須使用 tokio
Crate 中的 Mutex
和 mpsc
模組。
Speaker Notes
- 您的實作項目能否採用單一執行緒?