From 4cc8c691a3b5914eded43c2334ba9e8eb49cede1 Mon Sep 17 00:00:00 2001 From: Anders Nilsson <anders.nilsson@control.lth.se> Date: Wed, 18 Nov 2015 11:37:11 +0100 Subject: [PATCH] Implemented dining philosophers --- dining_philosophers/Cargo.lock | 4 +++ dining_philosophers/Cargo.toml | 4 +++ dining_philosophers/src/main.rs | 61 +++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 dining_philosophers/Cargo.lock create mode 100644 dining_philosophers/Cargo.toml create mode 100644 dining_philosophers/src/main.rs diff --git a/dining_philosophers/Cargo.lock b/dining_philosophers/Cargo.lock new file mode 100644 index 0000000..53372d9 --- /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 0000000..882f611 --- /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 0000000..538cc12 --- /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(); + } +} -- GitLab