1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
| // Copyright 2024 Google LLC
// SPDX-License-Identifier: Apache-2.0
use std::sync::Arc;
use tokio::sync::{Mutex, mpsc};
use tokio::time;
struct Chopstick;
struct Philosopher {
name: String,
// ANCHOR_END:哲学家
left_chopstick: Arc<Mutex<Chopstick>>,
right_chopstick: Arc<Mutex<Chopstick>>,
thoughts: mpsc::Sender<String>,
}
impl Philosopher {
async fn think(&self) {
self.thoughts
.send(format!("Eureka! {} has a new idea!", &self.name))
.await
.unwrap();
}
// ANCHOR_END:哲学家的思考
// 主播:哲学家吃
async fn eat(&self) {
// 继续努力,直到我们拥有双筷子
// ANCHOR_END:哲学家吃
// 拿起筷子...
let _left_chopstick = self.left_chopstick.lock().await;
let _right_chopstick = self.right_chopstick.lock().await;
// 锚:哲学家吃身体
println!("{} is eating...", &self.name);
time::sleep(time::Duration::from_millis(5)).await;
// ANCHOR_END:哲学家吃身体
// 锁掉在这里
// 锚:哲学家吃完
}
}
// tokio 调度程序不会与 5 个哲学家陷入僵局,因此有 2 个哲学家。
static PHILOSOPHERS: &[&str] = &["Socrates", "Hypatia"];
#[tokio::main]
async fn main() {
// ANCHOR_END:哲学家吃完
// 制作筷子
let mut chopsticks = vec![];
PHILOSOPHERS
.iter()
.for_each(|_| chopsticks.push(Arc::new(Mutex::new(Chopstick))));
// 创造哲学家
let (philosophers, mut rx) = {
let mut philosophers = vec![];
let (tx, rx) = mpsc::channel(10);
for (i, name) in PHILOSOPHERS.iter().enumerate() {
let mut left_chopstick = Arc::clone(&chopsticks[i]);
let mut right_chopstick =
Arc::clone(&chopsticks[(i + 1) % PHILOSOPHERS.len()]);
if i == PHILOSOPHERS.len() - 1 {
std::mem::swap(&mut left_chopstick, &mut right_chopstick);
}
philosophers.push(Philosopher {
name: name.to_string(),
left_chopstick,
right_chopstick,
thoughts: tx.clone(),
});
}
(philosophers, rx)
// tx 被删除在这里,所以我们以后不需要显式地删除它
};
// 让他们思考并吃饭
for phil in philosophers {
tokio::spawn(async move {
for _ in 0..100 {
phil.think().await;
phil.eat().await;
}
});
}
// 输出他们的想法
while let Some(thought) = rx.recv().await {
println!("Here is a thought: {thought}");
}
}
|