Dining philosophers question

⚓ Rust    📅 2025-11-09    👤 surdeus    👁️ 6      

surdeus

use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

#[derive(Clone)]
struct Philosopher {
    pub fork1: Arc<Mutex<usize>>,
    pub fork2: Arc<Mutex<usize>>,
    pub is_eating: bool,
    pub id: usize,
}

impl Philosopher {
    pub fn eat(&mut self) {
        {
            if let Ok(_) = self.fork1.lock() && let Ok(_) = self.fork2.lock() {
                self.is_eating = true;
                println!("Philosopher {} is eating!", self.id);
                thread::sleep(Duration::from_secs(1));
            }
        }
        self.is_eating = false;
    }
}

fn algo() {
    let forks: [Arc<Mutex<usize>>; 5] = core::array::from_fn(|x| Arc::new(Mutex::new(x)));
    let philosophers: [Arc<Mutex<Philosopher>>; 5] = core::array::from_fn(|x| Arc::new(Mutex::new(Philosopher {fork1: Arc::clone(&forks[x % 5]), fork2: Arc::clone(&forks[(x + 1) % 5]), is_eating: false, id: x})));
    let mut join_handles = Vec::new();
    for i in 0..5 {
        let value = philosophers.clone();
        let join_handle = thread::spawn(move || {
            let binding = Arc::clone(&value[i]);
            let mut philosopher = binding.lock().unwrap();
            loop {
                philosopher.eat();
            }
        });
        join_handles.push(join_handle);
    }
    for join_handle in join_handles {
        join_handle.join().unwrap();
    }
}

fn main() {
    algo();
}

The Dining Philosophers problem seems to have a string of locks followed by another.
Philosopher 1 is eating!
Philosopher 3 is eating!
Philosopher 1 is eating!
Philosopher 3 is eating!
Philosopher 3 is eating!
Philosopher 3 is eating!
Philosopher 3 is eating!
Philosopher 3 is eating!
Philosopher 3 is eating!
Philosopher 2 is eating!
Philosopher 2 is eating!
Philosopher 2 is eating!
Philosopher 2 is eating!
Philosopher 2 is eating!
Philosopher 2 is eating!
Philosopher 1 is eating!
Philosopher 1 is eating!
Philosopher 1 is eating!
I don't get why this happens.

7 posts - 3 participants

Read full topic

🏷️ Rust_feed