From e26bc568ac196e511fed9469fadc098aa1d100e8 Mon Sep 17 00:00:00 2001 From: julianknodt Date: Sat, 30 Mar 2024 19:25:48 -0700 Subject: [PATCH] Change example with race conditions --- FAQ.md | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/FAQ.md b/FAQ.md index 745f03399..96964a94b 100644 --- a/FAQ.md +++ b/FAQ.md @@ -211,15 +211,12 @@ this shortest route, you can just stop and avoid wasted effort. In sequential land, you might model this "best result" as a shared value like `Rc>` (here the `usize` represents the length of best path found so far); in parallel land, you'd use a `Arc`. -Now we can make our search function look like: ```rust -fn search(path: &Path, cost_so_far: usize, best_cost: &Arc) { - if cost_so_far >= best_cost.load(Ordering::SeqCst) { - return; - } - ... - best_cost.store(...); +fn search(path: &Path, cost_so_far: usize, best_cost: &AtomicUsize) { + let total_cost = cost_so_far + ...; + // Using `fetch_min` to avoid a race condition, in case it changed since `load`. + best_cost.fetch_min(cost_so_far, Ordering::SeqCst); } ```