Dining Philosophers — Async

See dining philosophers for a description of the problem.

As before, you will need a local Cargo installation for this exercise. Copy the code below to a file called src/main.rs, fill out the blanks, and test that cargo run does not deadlock:

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) {
            .send(format!("Eureka! {} has a new idea!", &self.name))

    async fn eat(&self) {
        // Keep trying until we have both forks
        println!("{} is eating...", &self.name);

static PHILOSOPHERS: &[&str] =
    &["Socrates", "Hypatia", "Plato", "Aristotle", "Pythagoras"];

async fn main() {
    // Create forks

    // Create philosophers

    // Make them think and eat

    // Output their thoughts

Since this time you are using Async Rust, you’ll need a tokio dependency. You can use the following Cargo.toml:

name = "dining-philosophers-async-dine"
version = "0.1.0"
edition = "2021"

tokio = { version = "1.26.0", features = ["sync", "time", "macros", "rt-multi-thread"] }

Also note that this time you have to use the Mutex and the mpsc module from the tokio crate.

This slide should take about 20 minutes.
  • Can you make your implementation single-threaded?