1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2024-12-15 06:20:32 +02:00

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
This commit is contained in:
Martin Geisler 2023-07-25 08:56:27 +02:00 committed by GitHub
parent bf3ffa23ee
commit 3c7659d59b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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(),
});
}