Demo entry 2843098

dining philosophers

   

Submitted by anonymous on Oct 17, 2015 at 23:31
Language: Rust. Code size: 1.3 kB.

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

struct Philosopher {
	name: String,
	left: usize,
	right: usize,
}

impl Philosopher {
	fn new(name: &str, left: usize, right: usize) -> Philosopher {
		Philosopher {
			name: name.to_string(),
			left: left,
			right: right,
		}
	}

	fn eat(&self, table: &Table) {
		let _left = table.forks[self.left].lock().unwrap();
		let _right = table.forks[self.right].lock().unwrap();

		println!("{} is eating.", self.name);

		thread::sleep_ms(1000);

		println!("{} is done eating.", self.name);
	}
}

struct Table {
	forks: Vec<Mutex<()>>,
}

fn main() {
    let table = Arc::new(Table { forks: vec![
    	Mutex::new(()),
    	Mutex::new(()),
    	Mutex::new(()),
    	Mutex::new(()),
    	Mutex::new(()),
    ]});

	let philosophers = vec! [
    	Philosopher::new("Kant", 0, 1),
	    Philosopher::new("Hegel", 1, 2),
	    Philosopher::new("Kierkegaard", 2, 3),
	    Philosopher::new("Nietzsche", 3, 4),
	    Philosopher::new("Heidegger", 0, 4),
	];

	let handles: Vec<_> = philosophers.into_iter().map(|p| {
        let table = table.clone();

		thread::spawn(move || {
			p.eat(&table);
		})
	}).collect();

	for h in handles {
		h.join().unwrap();
	}
}

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).