Skip to content

Commit db0b161

Browse files
authored
fix async Philosopher execise livelock error (#2372)
1 parent 7a6abee commit db0b161

File tree

1 file changed

+8
-22
lines changed

1 file changed

+8
-22
lines changed

src/concurrency/async-exercises/dining-philosophers.rs

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -43,26 +43,9 @@ impl Philosopher {
4343
async fn eat(&self) {
4444
// Keep trying until we have both forks
4545
// ANCHOR_END: Philosopher-eat
46-
let (_left_fork, _right_fork) = loop {
47-
// Pick up forks...
48-
let left_fork = self.left_fork.try_lock();
49-
let right_fork = self.right_fork.try_lock();
50-
let Ok(left_fork) = left_fork else {
51-
// If we didn't get the left fork, drop the right fork if we
52-
// have it and let other tasks make progress.
53-
drop(right_fork);
54-
time::sleep(time::Duration::from_millis(1)).await;
55-
continue;
56-
};
57-
let Ok(right_fork) = right_fork else {
58-
// If we didn't get the right fork, drop the left fork and let
59-
// other tasks make progress.
60-
drop(left_fork);
61-
time::sleep(time::Duration::from_millis(1)).await;
62-
continue;
63-
};
64-
break (left_fork, right_fork);
65-
};
46+
// Pick up forks...
47+
let _left_fork = self.left_fork.lock().await;
48+
let _right_fork = self.right_fork.lock().await;
6649

6750
// ANCHOR: Philosopher-eat-body
6851
println!("{} is eating...", &self.name);
@@ -89,8 +72,11 @@ async fn main() {
8972
let mut philosophers = vec![];
9073
let (tx, rx) = mpsc::channel(10);
9174
for (i, name) in PHILOSOPHERS.iter().enumerate() {
92-
let left_fork = Arc::clone(&forks[i]);
93-
let right_fork = Arc::clone(&forks[(i + 1) % PHILOSOPHERS.len()]);
75+
let mut left_fork = Arc::clone(&forks[i]);
76+
let mut right_fork = Arc::clone(&forks[(i + 1) % PHILOSOPHERS.len()]);
77+
if i == PHILOSOPHERS.len() - 1 {
78+
std::mem::swap(&mut left_fork, &mut right_fork);
79+
}
9480
philosophers.push(Philosopher {
9581
name: name.to_string(),
9682
left_fork,

0 commit comments

Comments
 (0)