Skip to content
Snippets Groups Projects
Commit 4cc8c691 authored by Anders Nilsson's avatar Anders Nilsson
Browse files

Implemented dining philosophers

parent 55ab436f
No related branches found
No related tags found
No related merge requests found
[root]
name = "dining_philosophers"
version = "0.1.0"
[package]
name = "dining_philosophers"
version = "0.1.0"
authors = ["Anders Nilsson <anders.nilsson@control.lth.se>"]
use std::thread;
use std::sync::{Mutex,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!("{} is eating.",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 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 Focault",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();
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment