哲学家就餐问题
哲学家用餐示例是一个典型的并发问题:
Five philosophers dine together at the same table. Each philosopher has their own place at the table. There is a chopstick between each plate. The dish served is spaghetti which requires two chopsticks to eat. Each philosopher can only alternately think and eat. Moreover, a philosopher can only eat their spaghetti when they have both a left and right chopstick. Thus two chopsticks will only be available when their two nearest neighbors are thinking, not eating. After an individual philosopher finishes eating, they will put down both chopsticks.
在本练习中,需要使用本地 Cargo 安装。将以下代码复制到名为 src/main.rs
的文件中,并填写空白的地方,然后测试 cargo run
不会死锁:
use std::sync::{Arc, Mutex, mpsc}; use std::thread; use std::time::Duration; struct Chopstick; struct Philosopher { name: String, // left_chopstick: ... // right_chopstick: ... // thoughts: ... } impl Philosopher { fn think(&self) { self.thoughts .send(format!("Eureka! {} has a new idea!", &self.name)) .unwrap(); } fn eat(&self) { // Pick up chopsticks... println!("{} is eating...", &self.name); thread::sleep(Duration::from_millis(10)); } } static PHILOSOPHERS: &[&str] = &["Socrates", "Hypatia", "Plato", "Aristotle", "Pythagoras"]; fn main() { // Create chopsticks // Create philosophers // Make each of them think and eat 100 times // Output their thoughts }
您可以使用以下 Cargo.toml
:
[package]
name = "dining-philosophers"
version = "0.1.0"
edition = "2024"
This slide should take about 20 minutes.
- Encourage students to focus first on implementing a solution that “mostly” works.
- The deadlock in the simplest solution is a general concurrency problem and highlights that Rust does not automatically prevent this sort of bug.