Skip to content

Instantly share code, notes, and snippets.

@Nnwww
Created February 11, 2016 15:11
Show Gist options
  • Save Nnwww/3fd63c24805e2eb3856d to your computer and use it in GitHub Desktop.
Save Nnwww/3fd63c24805e2eb3856d to your computer and use it in GitHub Desktop.
フォークの奪い合いの様子を可視化
// Dining Philosophers
use std::thread;
use std::time::Duration;
use std::sync::{Arc, Mutex};
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 l = table.forks[self.left].lock().unwrap();
println!("Fork {} is in the left hand of {}.", self.left, self.name);
thread::sleep(Duration::from_millis(150));
let r = table.forks[self.right].lock().unwrap();
println!("Fork {} is in the right hand of {}.", self.right, self.name);
println!("{} is eating.", self.name);
thread::sleep(Duration::from_millis(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 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();
}
}
@Nnwww
Copy link
Author

Nnwww commented Feb 11, 2016

Output

Fork 0 is in the left hand of Judith Butler.
Fork 2 is in the left hand of Karl Marx.
Fork 1 is in the left hand of Gilles Deleuze.
Fork 3 is in the left hand of Emma Goldman.
Fork 4 is in the right hand of Emma Goldman.
Emma Goldman is eating.
Emma Goldman is done eating.
Fork 3 is in the right hand of Karl Marx.
Karl Marx is eating.
Karl Marx is done eating.
Fork 2 is in the right hand of Gilles Deleuze.
Gilles Deleuze is eating.
Gilles Deleuze is done eating.
Fork 1 is in the right hand of Judith Butler.
Judith Butler is eating.
Judith Butler is done eating.
Fork 0 is in the left hand of Michel Foucault.
Fork 4 is in the right hand of Michel Foucault.
Michel Foucault is eating.
Michel Foucault is done eating.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment