summaryrefslogtreecommitdiff
path: root/examples/dining_philosophers.rs
diff options
context:
space:
mode:
authorMica White <botahamec@outlook.com>2024-03-09 17:48:04 -0500
committerMica White <botahamec@outlook.com>2024-03-09 17:48:04 -0500
commitff8c634a303d4a4133accf5fbff375046f022c7f (patch)
tree53f258c9571c6b987c51bed9c11377bb422c9a7a /examples/dining_philosophers.rs
parent0172ecb56f1f8c414ea16bee9865d23584d5894a (diff)
Dining Philosophers example
Diffstat (limited to 'examples/dining_philosophers.rs')
-rw-r--r--examples/dining_philosophers.rs68
1 files changed, 68 insertions, 0 deletions
diff --git a/examples/dining_philosophers.rs b/examples/dining_philosophers.rs
new file mode 100644
index 0000000..9600c8c
--- /dev/null
+++ b/examples/dining_philosophers.rs
@@ -0,0 +1,68 @@
+use std::{thread, time::Duration};
+
+use happylock::{LockCollection, Mutex, ThreadKey};
+
+static PHILOSOPHERS: [Philosopher; 5] = [
+ Philosopher {
+ name: "Socrates",
+ left: 0,
+ right: 1,
+ },
+ Philosopher {
+ name: "John Rawls",
+ left: 1,
+ right: 2,
+ },
+ Philosopher {
+ name: "Jeremy Bentham",
+ left: 2,
+ right: 3,
+ },
+ Philosopher {
+ name: "John Stuart Mill",
+ left: 3,
+ right: 4,
+ },
+ Philosopher {
+ name: "Judith Butler",
+ left: 4,
+ right: 0,
+ },
+];
+
+static FORKS: [Mutex<()>; 5] = [
+ Mutex::new(()),
+ Mutex::new(()),
+ Mutex::new(()),
+ Mutex::new(()),
+ Mutex::new(()),
+];
+
+struct Philosopher {
+ name: &'static str,
+ left: usize,
+ right: usize,
+}
+
+impl Philosopher {
+ fn cycle(&self) {
+ let key = ThreadKey::lock().unwrap();
+ thread::sleep(Duration::from_secs(1));
+ let forks = LockCollection::new([&FORKS[self.left], &FORKS[self.right]]).unwrap();
+ let forks = forks.lock(key);
+ println!("{} is eating...", self.name);
+ thread::sleep(Duration::from_secs(1));
+ println!("{} is done eating", self.name);
+ drop(forks);
+ }
+}
+
+fn main() {
+ let handles = PHILOSOPHERS
+ .iter()
+ .map(|philosopher| thread::spawn(move || philosopher.cycle()));
+
+ for handle in handles {
+ _ = handle.join();
+ }
+}