哲学家进餐 - 异步
查看哲学家进餐以获取问题的描述。
与之前一样,您需要一个本地的 Cargo 安装来进行这个练习。将下面的代码复制到一个名为 src/main.rs
的文件中,填写空白部分,并测试确保 cargo run
不会死锁:
use std::sync::Arc; use tokio::time; use tokio::sync::mpsc::{self, Sender}; use tokio::sync::Mutex; 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) { // Pick up forks... println!("{} is eating...", &self.name); time::sleep(time::Duration::from_millis(5)).await; } } static PHILOSOPHERS: &[&str] = &["Socrates", "Plato", "Aristotle", "Thales", "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
包的 Mutex
和 mpsc
模块。
- 您可以使您的实现为单线程吗?