Skip to content

Commit a4b8ac0

Browse files
committed
added concurrency tutorial
1 parent 3446739 commit a4b8ac0

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

philosophers/Cargo.lock

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

philosophers/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[package]
2+
name = "philosophers"
3+
version = "0.1.0"
4+
authors = ["Joel Abitan <[email protected]>"]

philosophers/src/main.rs

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
use std::thread;
2+
use std::sync::{Mutex, Arc};
3+
4+
struct Table {
5+
forks: Vec<Mutex<()>>,
6+
}
7+
8+
struct Philosopher {
9+
name: String,
10+
left: usize,
11+
right: usize,
12+
}
13+
14+
impl Philosopher {
15+
fn new(name: &str, left: usize, right: usize) -> Philosopher {
16+
Philosopher {
17+
name: name.to_string(),
18+
left: left,
19+
right: right,
20+
}
21+
}
22+
23+
fn eat(&self, table: &Table) {
24+
25+
let _left = table.forks[self.left].lock().unwrap();
26+
27+
thread::sleep_ms(150);
28+
29+
let _right = table.forks[self.right].lock().unwrap();
30+
31+
println!("{} is eating.", self.name);
32+
33+
thread::sleep_ms(1000);
34+
35+
println!("{} is done eating.", self.name );
36+
}
37+
}
38+
39+
fn main() {
40+
41+
let table = Arc::new(Table { forks: vec![
42+
Mutex::new(()),
43+
Mutex::new(()),
44+
Mutex::new(()),
45+
Mutex::new(()),
46+
Mutex::new(()),
47+
]});
48+
49+
let philosophers = vec![
50+
Philosopher::new("Judith Butler", 0, 1),
51+
Philosopher::new("Gilles Deleuze", 1, 2),
52+
Philosopher::new("Karl Max", 2, 3),
53+
Philosopher::new("Emma Goldman", 3, 4),
54+
Philosopher::new("Michel Foucault",0 ,4),
55+
];
56+
57+
let handles: Vec<_> = philosophers.into_iter().map(|p| {
58+
59+
let table = table.clone();
60+
61+
thread::spawn(move || {
62+
p.eat(&table);
63+
})
64+
}).collect();
65+
66+
for h in handles {
67+
h.join().unwrap();
68+
}
69+
}

0 commit comments

Comments
 (0)