Skip to content

Instantly share code, notes, and snippets.

@mrdaemon
Created September 1, 2015 10:45
Show Gist options
  • Save mrdaemon/9b99c1021f42cbeaeb3a to your computer and use it in GitHub Desktop.
Save mrdaemon/9b99c1021f42cbeaeb3a to your computer and use it in GitHub Desktop.
use std::thread;
use std::sync::Mutex;
use std::sync::Arc;
struct Table {
forks: Vec<Mutex<()>>,
}
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!("{} started stuffing germs in their mouth.", self.name);
thread::sleep_ms(1000);
println!("{} is done eating.", self.name);
}
}
fn main() {
let table = Arc::new(Table { forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
]});
let gross_men_in_togas = vec![
Philosopher::new("Plato", 0, 1),
Philosopher::new("Socrates", 1, 2),
Philosopher::new("Karl Marx", 2, 3),
Philosopher::new("Toga McThink", 3, 4),
Philosopher::new("Fourteen McDeep", 4, 0),
];
let handles: Vec<_> = gross_men_in_togas.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