From 3c7659d59bb987d5dcd2dbfea96bd44c4bef4858 Mon Sep 17 00:00:00 2001 From: Martin Geisler Date: Tue, 25 Jul 2023 08:56:27 +0200 Subject: [PATCH] Align dining-philosophers-async.rs with sync version (#1024) * Align dining-philosophers-async.rs with sync version This updates the version to use `std::mem::swap` like the synchronous version. * Apply suggestions from code review --- .../concurrency/dining-philosophers-async.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/exercises/concurrency/dining-philosophers-async.rs b/src/exercises/concurrency/dining-philosophers-async.rs index f5a31765..4518e79b 100644 --- a/src/exercises/concurrency/dining-philosophers-async.rs +++ b/src/exercises/concurrency/dining-philosophers-async.rs @@ -72,12 +72,18 @@ async fn main() { let mut philosophers = vec![]; let (tx, rx) = mpsc::channel(10); for (i, name) in PHILOSOPHERS.iter().enumerate() { - let left_fork = forks[i].clone(); - let right_fork = forks[(i + 1) % PHILOSOPHERS.len()].clone(); + let left_fork = Arc::clone(&forks[i]); + let right_fork = Arc::clone(&forks[(i + 1) % PHILOSOPHERS.len()]); + // To avoid a deadlock, we have to break the symmetry + // somewhere. This will swap the forks without deinitializing + // either of them. + if i == 0 { + std::mem::swap(&mut left_fork, &mut right_fork); + } philosophers.push(Philosopher { name: name.to_string(), - left_fork: if i % 2 == 0 { left_fork.clone() } else { right_fork.clone() }, - right_fork: if i % 2 == 0 { right_fork } else { left_fork }, + left_fork, + right_fork, thoughts: tx.clone(), }); }