Dining Philosophers — Async

برای توضیح مشکل به dining philosophers مراجعه کنید.

مانند قبل، برای این تمرین به Cargo installation](../../cargo/running-locally.md) نیاز دارید. کد زیر را در فایلی به نام src/main.rs کپی کنید، جاهای خالی را پر کنید و تست کنید که cargo run به بن بست (src/main.rs) نمی‌خورد:

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!("ایول! {} یک ایده جدید!", &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 }

از آنجایی که این بار از Async 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"] }

همچنین توجه داشته باشید که این بار باید از ماژول Mutex و mpsc از tokio crate استفاده کنید.

Speaker Notes

This slide should take about 20 minutes.
  • آیا می‌توانید پیاده‌سازی خود را تک thread ای کنید؟