diff --git a/dining_philosophers/Cargo.lock b/dining_philosophers/Cargo.lock new file mode 100644 index 0000000000000000000000000000000000000000..53372d9d0ed1896e487a417d8170f4eea8c56f67 --- /dev/null +++ b/dining_philosophers/Cargo.lock @@ -0,0 +1,4 @@ +[root] +name = "dining_philosophers" +version = "0.1.0" + diff --git a/dining_philosophers/Cargo.toml b/dining_philosophers/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..882f61170815a28a433f843d832bcb582b44f78a --- /dev/null +++ b/dining_philosophers/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "dining_philosophers" +version = "0.1.0" +authors = ["Anders Nilsson <anders.nilsson@control.lth.se>"] diff --git a/dining_philosophers/src/main.rs b/dining_philosophers/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..538cc12db1a5a0b6c3fe6b432e56fb74bc1f6b97 --- /dev/null +++ b/dining_philosophers/src/main.rs @@ -0,0 +1,61 @@ +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(); + } +}