Created
December 28, 2015 01:16
-
-
Save danmactough/e258404cae0ab956f8ff to your computer and use it in GitHub Desktop.
Dining Philosophers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "dining_philosophers" | |
version = "0.1.0" | |
authors = ["Dan MacTough <[email protected]>"] | |
[dependencies] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
thread::sleep_ms(150); | |
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("Judith Butler", 0, 1), | |
Philosopher::new("Gilles Deleuze", 1, 2), | |
Philosopher::new("Karl Marx", 2, 3), | |
Philosopher::new("Emma Goldman", 3, 4), | |
Philosopher::new("Michel Foucault", 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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment