Skip to content

Commit

Permalink
Change example with race conditions
Browse files Browse the repository at this point in the history
  • Loading branch information
JulianKnodt committed Apr 3, 2024
1 parent cf167b6 commit e26bc56
Showing 1 changed file with 4 additions and 7 deletions.
11 changes: 4 additions & 7 deletions FAQ.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Cell<usize>>` (here the `usize` represents the length of best
path found so far); in parallel land, you'd use a `Arc<AtomicUsize>`.
Now we can make our search function look like:

```rust
fn search(path: &Path, cost_so_far: usize, best_cost: &Arc<AtomicUsize>) {
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);
}
```

Expand Down

0 comments on commit e26bc56

Please sign in to comment.