Dining Philosophers --- Async

See dining philosophers for a description of the problem.

前と同様に、この演習でもローカルの 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() {
    // フォークを作成する

    // 哲学者を作成する

    // 哲学者が思索と食事を行うようにする

    // 哲学者の思索を出力する
}

今回は非同期 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 モジュールを使用する必要があることにも注意してください。

This slide should take about 20 minutes.
  • 実装をシングルスレッドにできますか?