食事する哲学者 — Async
問題の説明については、食事する哲学者 を参照してください。
前回と同様に、この演習にはローカルの Cargo のインストール が必要です。以下の コードを src/main.rs というファイルにコピーし、空欄を埋めて、 cargo run がデッドロックしないことを確認してください:
// Copyright 2024 Google LLC // SPDX-License-Identifier: Apache-2.0 use std::sync::Arc; use tokio::sync::{Mutex, mpsc}; use tokio::time; struct Chopstick; struct Philosopher { name: String, // left_chopstick: ... // right_chopstick: ... // 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 chopsticks println!("{} is eating...", &self.name); time::sleep(time::Duration::from_millis(5)).await; } } // tokio scheduler doesn't deadlock with 5 philosophers, so have 2. static PHILOSOPHERS: &[&str] = &["Socrates", "Hypatia"]; #[tokio::main] async fn main() { // 箸を作成する // 哲学者を作成する // 考えたり食べたりさせる // 彼らの考えを出力する }
今回は Async Rust を使用するため、tokio への依存関係が必要です。次の Cargo.toml を使用できます:
[package]
name = "dining-philosophers-async-dine"
version = "0.1.0"
edition = "2024"
[dependencies]
tokio = { version = "1.26.0", features = ["sync", "time", "macros", "rt-multi-thread"] }
また、今回は tokio クレートの Mutex と mpsc モジュールを使用しなければならない点にも注意してください。
- 実装をシングルスレッドにできますか?